【问题标题】:Injecting settings into EF core context in class library将设置注入类库中的 EF 核心上下文
【发布时间】:2019-06-21 12:09:39
【问题描述】:

我的 API 项目的 appsettings.json 中有我的连接字符串,我想在我的数据库项目的上下文中使用它。通常,依赖注入可以解决问题,但是,当我运行迁移时,我会收到此错误:

无法创建“上下文”类型的对象。对于不同的 设计时支持的模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728!

在上下文中硬编码连接字符串可以解决这个问题,但对我来说不是一个可行的解决方案,因为我需要根据环境更改连接字符串。请参阅 API 项目中的 ConfigureServices 方法和数据库项目中的上下文。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed
        // for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    services.AddDbContext<Context>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public class Context : DbContext
{
    private readonly IOptions<AppSettings> _settings;

    public Context(IOptions<AppSettings> settings) : base()
    {
        _settings = settings;
    }

    public Context(IOptions<AppSettings> settings, DbContextOptions<Context> options) : base(options)
    {
        _settings = settings;
    }

    ***DBSets***

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_settings.Value.DBConnectionString);
    }
}

【问题讨论】:

  • 这是因为_settings.Value.DBConnectionString 没有得到连接字符串。
  • 我知道这是问题所在,我在系统的其他部分使用了相同的技术,并且它在那里工作。
  • Startup类中将optionsBuilder.UseSqlServer(_settings.Value.DBConnectionString);代码移动到ConfigureServices方法有问题吗?如果没有,我可以给出一个解决方案。
  • 是的,这是一个问题,因为我必须在多个地方使用连接字符串初始化上下文,即我的测试项目。 OnConfiguring 方法中的解决方案将是最佳的。

标签: c# dependency-injection .net-core entity-framework-core


【解决方案1】:

在 .NET Core 中最简单的方法如下:

services.AddDbContext<Context>(options => {
    options.UseSqlServer(Configuration.GetConnectionString("<key in appsettings>"));
});

您的Context 类确实应该继承DbContext。 这也将允许对您的Context 进行依赖注入。

你的应用设置应该像这样:

"ConnectionStrings"  : {
    "<key in appsettings>" : "<connection string>"
},

ConnectionStrings 在设置 json 中位于根级别。

【讨论】:

    【解决方案2】:

    我找到了解决办法,请看下文。

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using System;
    
    namespace Database
    {
        public class Context : DbContext
        {
            public Context() : base()
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                             .SetBasePath(AppDomain.CurrentDomain.BaseDirectory + @"..\..\..\..\")
                             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();
    
                ConnectionString = configuration.GetConnectionString("Database");
            }
    
            public string ConnectionString { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(ConnectionString);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2017-09-19
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多