如何在ABP服务中获取DbContext?

时间:2019-09-03 13:10:17

标签: c# asp.net-core dbcontext asp.net-boilerplate abp

如何在应用程序层中获取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实例并将其注入?

1 个答案:

答案 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;
    }
}