I've created a project App.Data
that contains domain objects and a base class that implements IDbContextFactory<T>
for creating a DbContext
. The code is available here.
Generating the migrations in a seperate assembly works well.
What I would like to utilize the context I've created in App.Data.Sql
that is created via an SqlDbContextFactory<MyAppDbContext>
when registering entity framework within asp.net mvc.
What I want to have is something like
services.AddEntityFrameworkSqlServer()
.AddDbContext(typeof(SqlDbContextFactory<MyAppDbContext>))
Registering it as a singleton doesn't work since when resolved complains about no provider has been configured.
services.AddSingleton<IDbContextFactory<..>, SqlDbContextFactory<..>>();
services.AddScoped<MyApp..>(p => p.GetRequiredService<IDb..>().Create());
Instead of .AddDbContext(typeof(...))
provide a factory method to create context:
services.AddTransient(provider =>
{
//if needed: anything from DI
var bar = provider.GetService<TBar>();
//if needed: external captured variable
doSomething(service);
//explicit context creation
return new FooDbContext(...);
});