Skip to content

Instantly share code, notes, and snippets.

@merken
Created September 25, 2019 19:34
Show Gist options
  • Save merken/c2654183b652d4f816f3bc3680ee1632 to your computer and use it in GitHub Desktop.
Save merken/c2654183b652d4f816f3bc3680ee1632 to your computer and use it in GitHub Desktop.
UseEFInterceptor
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