Created
September 25, 2019 19:34
-
-
Save merken/c2654183b652d4f816f3bc3680ee1632 to your computer and use it in GitHub Desktop.
UseEFInterceptor
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
private static IServiceCollection UseEFInterceptor<T>(this IServiceCollection services, IConfiguration configuration) | |
where T : class, IInterceptor | |
{ | |
return services | |
.AddScoped<DbContextOptions>((serviceProvider) => | |
{ | |
var tenant = serviceProvider.GetRequiredService<TenantInfo>(); | |
var efServices = new ServiceCollection(); | |
efServices.AddEntityFrameworkSqlServer(); | |
efServices.AddScoped<TenantInfo>(s => | |
serviceProvider.GetRequiredService<TenantInfo>()); // Allows DI for tenant info, set by parent pipeline via middleware | |
efServices.AddScoped<IInterceptor, T>(); // Adds the interceptor | |
var connectionString = configuration.GetConnectionString("SqlServerConnection"); | |
return new DbContextOptionsBuilder<ProductsDbContext>() | |
.UseInternalServiceProvider(efServices.BuildServiceProvider()) | |
.UseSqlServer(connectionString) | |
.Options; | |
}) | |
.AddScoped<ProductsDbContext>(s => new ProductsDbContext(s.GetRequiredService<DbContextOptions>())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment