0

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 :)

pietro
  • 143
  • 1
  • 9
  • Why not open an issue on the project repo? – David L Aug 15 '22 at 21:44
  • EF contexts are units of work, you shouldn't cache them. Instead let your ODBC driver handle connection pool caching, create your contexts and destroy them as soon as you're done! – Blindy Aug 16 '22 at 14:51

1 Answers1

3

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.

Christian Held
  • 2,321
  • 1
  • 15
  • 26