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 :)
Asked
Active
Viewed 1,154 times
0
-
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 Answers
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
-
Hello, thank you very much. And can you help me with di registration please? Thank you :) – pietro Aug 16 '22 at 21:23