ConnectionString from appsettings.json in Data Tier with Entity Framework Core entity-framework-core


I have a new application that I am building on ASP.NET Core with Entity Framework Core. The application has a UI, model, business, and data tier. In previous versions of ASP.NET, you could set the connection string in the web.config and it would be available in referenced tiers by default. This does not appear to be the same case in ASP.NET Core with appsettings.json (or other config options)? Any idea on how this is accomplished? I have the dbcontext configured in the data layer, but I am current hard-coding the connection string.

All examples I have see out there has the dbcontext configured in the UI layer in startup.cs. This is what I am trying to avoid.

The question Here got off topic.

5/23/2017 10:30:56 AM

Accepted Answer

You can easily add an extension method of IServiceCollection into your business/services layer and use it to register its own dependencies. Then in the startup you just call the method on the service layer without having any reference to EntityFramework in your web app.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace your.service.layer
    public static class MyServiceCollectionExtensions
        public static IServiceCollection AddMyServiceDependencies(this IServiceCollection services, string connectionString)
            .AddDbContext<YourDbContext>((serviceProvider, options) =>
             return services;



using your.service.layer;

public void ConfigureServices(IServiceCollection services)
    var connectionString = Configuration.GetConnectionString("EntityFrameworkConnectionString");

Now your web app only needs a reference to your business/service layer and it is not directly dependent on EntityFramework.

5/29/2018 5:30:19 PM

Related Questions


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