如何获取ABP服务中的DbContext?
How to get DbContext in ABP service?
如何在应用层获取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
实例并注入它?
不要在构造函数中调用dbContextProvider.GetDbContext()
。
将 _ctx
实现为 getter 并在您实际需要上下文的任何地方使用它。
public class SeedingTestDataAppService : MyAppServiceBase
{
private MyDbContext _ctx => _dbContextProvider.GetDbContext();
private readonly IDbContextProvider<MyDbContext> _dbContextProvider;
public SeedingTestDataAppService(IDbContextProvider<MyDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
}
如何在应用层获取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
实例并注入它?
不要在构造函数中调用dbContextProvider.GetDbContext()
。
将 _ctx
实现为 getter 并在您实际需要上下文的任何地方使用它。
public class SeedingTestDataAppService : MyAppServiceBase
{
private MyDbContext _ctx => _dbContextProvider.GetDbContext();
private readonly IDbContextProvider<MyDbContext> _dbContextProvider;
public SeedingTestDataAppService(IDbContextProvider<MyDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
}