【问题标题】:How to get DbContext in ABP service?如何在 ABP 服务中获取 DbContext?
【发布时间】:2019-09-03 13:10:17
【问题描述】:

如何在应用层获取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 实例并注入它?

【问题讨论】:

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


    【解决方案1】:

    不要在构造函数中调用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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多