0

如何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实例并注入它?

4

1 回答 1

2

不要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;
    }
}
于 2019-09-03T14:52:44.560 回答