在多项目 ASP Core 1 解决方案中配置 Entity Framework

Configuring Entity Framework in multiproject ASP Core 1 solution

我有两个项目:appsetting.json 中包含连接字符串的 Web 项目和包含一些实现业务逻辑的存储库的域项目。现在我需要将连接字符串从 Web 传递到域项目。首先,我通过 this article 中描述的方法从配置中获得了连接字符串值,但我如何将它传递到域中?在以前的 ASP 版本中,我可以通过 ConfigurationManager 来完成,但现在不可能了。

我的 DomainDbContext:

public class DomainDbContext : DbContext {
    public DbSet<SomeEntity> SomeEntities{ get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder builder) {
        builder.UseNpgsql(@"HardcodedConnectionString");
    }
}

它曾经像

public List<SomeEntityDto> GetAll() {
    using(var context = new DomainDbContext()) {
        return AutoMapperHelper.Mapper.Map<List<SomeEntityDto>>(context.SomeEntities.ToList());
    }
}

在控制器提供者调用中

public class SomeController : Controller {
    private readonly AppSettings _settings;
    private readonly ISomeProvider _someProvider;
    public OrderController( IOptions<AppSettings> settings,
                            ISomeProvider someProvider) {
        _settings = settings.Value;
        _someProvider = someProvider;
    }
    public ActionResult Index() {
        return View("Index", new SomeModel {
            someEntities = _someProvider.GetAll()
        });
    }
}

在 EF7 中配置上下文和 EF 的一般方式(自从您提到 .NET Core 以来,我假设您使用的是这种方式)与以前的版本相比发生了变化。一种方法是像您已经完成的那样重写 OnConfiguring 方法。然而,最常见的方法是为 DbContext 构造函数提供选项,这将允许您在 Web 项目中配置 EF 并传递连接字符串:

public class DomainDbContext : DbContext
{
    public DomainDbContext(DbContextOptions options) : base(options)
    { }
}

然后在 Startup.cs 您的 Web 项目中,您可以按如下方式配置 DbContext:

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<DomainDbContext>(o => o.UseSqlServer(Configuration["ConnectionStrings:DomainDb"]));
}

您需要根据 appsettings.json 调整 "ConnectionStrings:DomainDb"。为了使上面的工作正常,它应该看起来类似于:

{
  "ConnectionStrings": {
    "DomainDb": "Data Source=.\SQLSERVER;Initial Catalog=DomainDb;Integrated Security=SSPI;"
  }
}

First i have got connection string value from config via method described in this article, but how i can pass it into Domain?

你不应该这样做。如果您的域中需要 DbContext,那么您的域层也存在缺陷。域必须是持久性无知的。您通常通过存储库获得这种抽象。否则你的域取决于你的基础设施。

其次,最好通过依赖注入解决所有问题,然后所有配置问题都取决于应用程序,而不是您的域的关注点。

In previous version of ASP i could do it via ConfigurationManager, but now its imposible

这仍然违反 DDD,因为 ConfigurationManager 是基础设施(非常非常特定于 ASP.NET)并且不属于您的域。

理想情况下,您只需将 DbContext 传递给提供者 class 构造函数。如果你不能(你的提供者的生命周期比你的 DbContext 长),传递一个解析 DbContext 的工厂,然后按需解析它。

using(var dbContext = this.dbContextFactory.Create()) 
{
}