/** Create tenant middleware to get tenant name from connection string. Assign tenant name value to property of TenantInfo object registered in DI container in Startup.cs */ public class TenantMiddleware { private readonly RequestDelegate next; public TenantMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { if (!context.Request.Query.TryGetValue("tenant", out StringValues tenantParam)) { await context.WriteResponse("Invalid Tenant parameter", StatusCodes.Status400BadRequest); return; } var tenantInfo = context.RequestServices.GetRequiredService(); tenantInfo.TenantName = tenantParam.ToString(); await next.Invoke(context); } } /** Inject TenantInfo object with tenant name into repository and build tenant aware connection string */ public class Repository { private readonly string tenantAwareConnString; private readonly ITenantAwareConnStringBuilder tenantAwareConnStringBuilder; public Repository(IDbConfigProvider dbConfigProvider, TenantInfo tenantInfo, ITenantAwareConnStringBuilder tenantAwareConnStringBuilder) { this.tenantAwareConnStringBuilder = tenantAwareConnStringBuilder; tenantAwareConnString = tenantAwareConnStringBuilder. .UseServer(dbConfigProvider.Server) .UseCredentials(dbConfigProvider.Username, dbConfigProvider.Password) .ForTenant(tenantInfo.TenantName) .Build(); } }