ajs117
ajs117

Reputation: 93

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

Upvotes: 1

Views: 1626

Answers (2)

ajs117
ajs117

Reputation: 93

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

Upvotes: 0

Glubus
Glubus

Reputation: 2855

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.

Upvotes: 1

Related Questions