如何在应用程序层中获取DbContext
实例?
我尝试过:
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
}
}
我不擅长ABP。我在哪里以及如何获取DbContext
实例并将其注入?
答案 0 :(得分:1)
请勿在构造函数中调用dbContextProvider.GetDbContext()
。
将_ctx
用作吸气剂,并在实际需要上下文的地方使用它。
public class SeedingTestDataAppService : MyAppServiceBase
{
private MyDbContext _ctx => _dbContextProvider.GetDbContext();
private readonly IDbContextProvider<MyDbContext> _dbContextProvider;
public SeedingTestDataAppService(IDbContextProvider<MyDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
}