Injecting settings into EF core context in class library

.net-core c# dependency-injection entity-framework-core

Question

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);
    }
}
1
1
1/28/2019 1:42:23 PM

Accepted Answer

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);
        }
    }
}
0
1/31/2019 10:11:36 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow