Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Multitenant.Models;
using MultiTenant.Data.Interfaces;
namespace Multitenant.Data
{
public class DbContextFactory : IDbContextFactory
{
public ApplicationDbContext CreateDbContext(Tenant tenant, IConfiguration configuration)
{
var options = new DbContextOptions<ApplicationDbContext>();
var dbContextOptionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>(options);
return new ApplicationDbContext(dbContextOptionsBuilder.Options, configuration, tenant);
}
}
}
using Microsoft.Extensions.Configuration;
using Multitenant.Data;
using Multitenant.Models;
namespace MultiTenant.Data.Interfaces
{
public interface IDbContextFactory
{
ApplicationDbContext CreateDbContext(Tenant tenant, IConfiguration confifuration);
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Multitenant.Providers;
using MultiTenant.Data.Interfaces;
namespace Multitenant
{
public static class StartupExtension
{
public static void EnsureMigrationsRun(this IApplicationBuilder app, IConfiguration configuration)
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContextFactory = serviceScope.ServiceProvider.GetService<IDbContextFactory>();
var allTenants = serviceScope.ServiceProvider.GetService<ITenantProvider>().AllTenants;
foreach (var tenant in allTenants)
{
var context = dbContextFactory.CreateDbContext(tenant, configuration);
context.Database.Migrate();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment