简体   繁体   English

如何在 Autofac json 配置文件中配置 DbContext

[英]How do I configure the DbContext in an Autofac json configuration file

ENV: VS 2019, C# .NET Framework 4.6.1 ENV:VS 2019,C# .NET 框架 4.6.1

I'm using a .json file to hold all my configurations:我正在使用.json文件来保存我的所有配置:

IConfigurationBuilder config = new ConfigurationBuilder();
        config.AddJsonFile("autofac.json");

My question is, how do I include the DbContext in this file?我的问题是,如何在这个文件中包含DbContext I'm adding Autofac to an existing application and using it in a new section.我将 Autofac 添加到现有应用程序并在新部分中使用它。 This is what the code looks like (change the real name to "My*" to protect the innocent) in the original code:原代码中的代码是这样的(把真名改成“My*”保护无辜):

public partial class MyDbContext : DbContext, IDisposable
{
    public MyDbContext () : base("MyDB")
    {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {}
}

Is it possible to relate the DbContext concrete class to an existing interface (does one exist) or should I create a wrapper around it and then create a corresponding interface for the wrapper class?是否可以将DbContext具体 class 与现有接口(是否存在)相关联,或者我应该围绕它创建一个包装器,然后为包装器 class 创建一个相应的接口?

The typical practice is to put connection info (eg a connection string) into the configuration file, not the JSON representation of a service class such as a DbContext ).典型的做法是将连接信息(例如连接字符串)放入配置文件,而不是服务 class (例如DbContext )的 JSON 表示。

You can then inject the concrete context (or, better , an IDbContextFactory that creates the MyDbContext .然后,您可以注入具体的上下文(或者,更好的是,一个创建MyDbContextMyDbContext

It becomes very problematic very quickly to provide non-configuration things in a configuration file (eg repos, service classes, EF resources, etc.) Stick to configuration alone.在配置文件中提供非配置内容(例如 repos、服务类、EF 资源等)很快就会变得非常有问题。坚持单独配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM