Skip to content

Instantly share code, notes, and snippets.

@codeprefect
Created November 29, 2019 19:52
Show Gist options
  • Save codeprefect/4fae3d712a0fe6308b1e39006c753feb to your computer and use it in GitHub Desktop.
Save codeprefect/4fae3d712a0fe6308b1e39006c753feb to your computer and use it in GitHub Desktop.
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