Register EF Core using IDbContextFactory in ASP.NET Core Mvc

asp.net-core-mvc c# entity-framework-core

Question

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());
1
1
5/18/2017 9:06:48 PM

Popular Answer

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(...);
});
1
5/18/2017 9:06:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow