How to get DbContext
instance in application layer?
I tried:
1.
public class SeedingTestDataAppService : MyAppServiceBase
{
private readonly MyDbContext _ctx;
public SeedingTestDataAppService
(
MyDbContext context // Error
)
{
_ctx = context;
}
}
2.
public class SeedingTestDataAppService : MyAppServiceBase
{
private readonly MyDbContext _ctx;
public SeedingTestDataAppService
(
IDbContextProvider<MyDbContext> dbContextProvider
)
{
_ctx = dbContextProvider.GetDbContext();
// Error: unitOfWork is null
}
}
I am not good at ABP. Where and how can I take a DbContext
instance and inject it?
Do not call dbContextProvider.GetDbContext()
in the constructor.
Implement _ctx
as a getter and use it wherever you actually need the context.
public class SeedingTestDataAppService : MyAppServiceBase
{
private MyDbContext _ctx => _dbContextProvider.GetDbContext();
private readonly IDbContextProvider<MyDbContext> _dbContextProvider;
public SeedingTestDataAppService(IDbContextProvider<MyDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
}