简体   繁体   English

将设置注入到类库中的EF核心上下文中

[英]Injecting settings into EF core context in class library

I have my connection string in appsettings.json in my API project which I want use in my context in my Database project. 我的API项目中的appsettings.json中有我的连接字符串,我想在我的数据库项目中的上下文中使用它。 Usually, dependency injection does the trick, however, when I run migrations I get this error: 通常,依赖注入可以解决问题,但是,当我运行迁移时,会出现以下错误:

Unable to create an object of type 'Context'. 无法创建“上下文”类型的对象。 For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ! 有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728

Hard-coding the connection string in the context fixes this problem but is not a viable solution for me as I need to change the connection string depending on environment. 在上下文中对连接字符串进行硬编码可解决此问题,但对我而言,这不是一个可行的解决方案,因为我需要根据环境更改连接字符串。 Please see my ConfigureServices method from the API project and the context from the Database project. 请从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);
    }
}

The easiest way to do it in .NET Core is the following: 在.NET Core中最简单的方法如下:

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

Your Context class indeed should inherit DbContext . 您的Context类确实应该继承DbContext This will also allow dependency injection of your Context . 这也将允许对Context进行依赖注入。

Your appsettings should like like: 您的应用设置应如下所示:

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

where ConnectionStrings is at root level in the settings json. 其中ConnectionStrings在设置json中位于根级别。

I have found a solution, please see below. 我找到了解决方案,请参阅下文。

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);
        }
    }
}

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

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