Created
November 29, 2019 19:52
-
-
Save codeprefect/4fae3d712a0fe6308b1e39006c753feb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Configuration; | |
using Multitenant.Data; | |
using Multitenant.Models; | |
namespace MultiTenant.Data.Interfaces | |
{ | |
public interface IDbContextFactory | |
{ | |
ApplicationDbContext CreateDbContext(Tenant tenant, IConfiguration confifuration); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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