i created my own dbcontextfactory and now i don't know how to correctly register it in di. Can you somebody help me please? IApplicationDbContext is just interfaces with db sets. I have register ma DbContext as pooled db context factory
builder.Services.AddPooledDbContextFactory<MyContext>(options =>
{
....
});
Interface of my db factory
interface IApplicationDbContextFactory
{
IApplicationDbContext CreateDbContext();
}
Implementation db factory
public class MyContextFactory<TContext> : IApplicationDbContextFactory where TContext : DbContext, IApplicationDbContext
{
private readonly IDbContextFactory<TContext> _dbContextFactory;
public MyContextFactory(IDbContextFactory<TContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
public IApplicationDbContext CreateDbContext()
{
return _dbContextFactory.CreateDbContext();
}
}
How can i correctly register my factory to di? Thank you
CodePudding user response:
Lifetime for the factory registered by AddPooledDbContextFactory
is Singleton
. Just register it with builder.Services.AddSingleton<IApplicationDbContextFactory, MyContextFactory<MyContext>>();
(though Scoped
and Transient
should also work just as fine):
var serviceCollection = new ServiceCollection();
serviceCollection.AddPooledDbContextFactory<SomeContext>(builder => builder.UseSqlite($"Filename={nameof(SomeContext)}.db"));
serviceCollection.AddSingleton<IApplicationDbContextFactory, MyContextFactory<SomeContext>>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var dbContextFactory = serviceProvider.GetRequiredService<IDbContextFactory<SomeContext>>();
using (var scope = serviceProvider.CreateScope())
{
var applicationDbContextFactory = serviceProvider.GetRequiredService<IApplicationDbContextFactory>();
var applicationDbContext = applicationDbContextFactory.CreateDbContext();
}
public class SomeContext : DbContext, IApplicationDbContext
{
public SomeContext(DbContextOptions<SomeContext> options) : base(options)
{
}
public DbSet<MyEntity> Entities { get; set; }
}
interface IApplicationDbContextFactory
{
IApplicationDbContext CreateDbContext();
}
public interface IApplicationDbContext
{
}
public class MyContextFactory<TContext> : IApplicationDbContextFactory where TContext : DbContext, IApplicationDbContext
{
private readonly IDbContextFactory<TContext> _dbContextFactory;
public MyContextFactory(IDbContextFactory<TContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
public IApplicationDbContext CreateDbContext()
{
return _dbContextFactory.CreateDbContext();
}
}