pietro
pietro

Reputation: 175

.NET DbContext or DbContextFactory

i use clean architecture - https://github.com/jasontaylordev/CleanArchitecture. And im stuck on one problem. I would like use DbContextFactory. But it's problem here. Because DbContext interface - IApplicationDbContext is declared in project Application. Real DbContext is in Infrastructure project. So i cannot use DbContextFactory because i cannot use something like this IDbContextFactory. Can somebody help me please? I'm really distressed of this. Thank you :)

Upvotes: -1

Views: 2725

Answers (1)

Christian Held
Christian Held

Reputation: 2828

One way would be to build your own factory abstraction and use the EF Core IDbContextFactory<TContext> in the implementation:

public interface IApplicationDbContextFactory
{
    IApplicationDbContext CreateDbContext();
}

and then use EF Core's IDbContextFactory in the implementation:

public class ApplicationDbContextFactory<TContext> : IApplicationDbContextFactory 
    where TContext : IApplicationDbContext
{
    private readonly IDbContextFactory<TContext> _factory;

    public ApplicationDbContextFactory(IDbContextFactory<TContext> factory)
    {
        _factory = factory;
    }

    public IApplicationDbContext CreateDbContext() => _factory.CreateDbContext();
}

To register the interface in DI you need to register IDBContextFactory using the AddDbContextFactory extension method

// Register EF Core DB Context Factory
services.AddDbContextFactory<ApplicationDbContext>(options => 
{
    // Your configuration
});

services.AddSingleton<IApplicationDbContextFactory, ApplicationDbContextFactory>();

Because IDbContextFactory is registered with singleton lifetime (by default) IApplicationDbContextFactory is also registered as singleton.

Keep in mind that if you change lifetime of the IDbContextFactory to update the IApplicationDbContextFactory service registration accordingly.

Upvotes: 5

Related Questions