Skip to content

Instantly share code, notes, and snippets.

@merken
Created September 25, 2019 19:46
Show Gist options
  • Save merken/dbd638debddbc01d08e6b1b786deb653 to your computer and use it in GitHub Desktop.
Save merken/dbd638debddbc01d08e6b1b786deb653 to your computer and use it in GitHub Desktop.
UseConnectionPerTenant
public static IServiceCollection UseConnectionPerTenant(this IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<ProductsDbContext>((serviceProvider) =>
{
var tenant = serviceProvider.GetRequiredService<TenantInfo>(); // Get from parent service provider (ASP.NET MVC Pipeline)
var connectionString = configuration.GetConnectionString(tenant.Name);
var options = new DbContextOptionsBuilder<ProductsDbContext>()
.UseSqlServer(connectionString)
.Options;
var context = new ProductsDbContext(options);
return context;
});
return services;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment