Facebook
From Stained Tapir, 4 Years ago, written in C#.
Embed
Download Paste or View Raw
Hits: 171
  1. /**
  2.         Create tenant middleware to get tenant name from connection string.
  3.         Assign tenant name value to property of TenantInfo object registered in DI container in Startup.cs
  4. */
  5. public class TenantMiddleware
  6. {
  7.   private readonly RequestDelegate next;
  8.  
  9.   public TenantMiddleware(RequestDelegate next)
  10.   {
  11.     this.next = next;
  12.   }
  13.  
  14.   public async Task Invoke(HttpContext context)
  15.   {
  16.     if (!context.Request.Query.TryGetValue("tenant", out StringValues tenantParam))
  17.     {
  18.       await context.WriteResponse("Invalid Tenant parameter", StatusCodes.Status400BadRequest);
  19.       return;
  20.     }
  21.    
  22.     var tenantInfo = context.RequestServices.GetRequiredService<TenantInfo>();
  23.     tenantInfo.TenantName = tenantParam.ToString();
  24.    
  25.     await next.Invoke(context);
  26.   }
  27. }
  28.  
  29. /**
  30.         Inject TenantInfo object with tenant name into repository and build tenant aware connection string  
  31. */
  32.  
  33. public class Repository
  34. {
  35.   private readonly string tenantAwareConnString;
  36.   private readonly ITenantAwareConnStringBuilder tenantAwareConnStringBuilder;
  37.  
  38.   public Repository(IDbConfigProvider dbConfigProvider, TenantInfo tenantInfo, ITenantAwareConnStringBuilder tenantAwareConnStringBuilder)
  39.   {
  40.     this.tenantAwareConnStringBuilder = tenantAwareConnStringBuilder;
  41.     tenantAwareConnString = tenantAwareConnStringBuilder.
  42.       .UseServer(dbConfigProvider.Server)
  43.       .UseCredentials(dbConfigProvider.Username, dbConfigProvider.Password)
  44.       .ForTenant(tenantInfo.TenantName)
  45.       .Build();
  46.   }
  47. }