简体   繁体   中英

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. 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 !

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.

// 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:

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

Your Context class indeed should inherit DbContext . This will also allow dependency injection of your Context .

Your appsettings should like like:

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

where ConnectionStrings is at root level in the settings 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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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