Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConnectionString from appsettings.json in Data Tier with 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.

like image 847
Solomon Shaffer Avatar asked Jul 13 '16 16:07

Solomon Shaffer


1 Answers

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)
        {
             services.AddEntityFrameworkSqlServer()
            .AddDbContext<YourDbContext>((serviceProvider, options) =>
            options.UseSqlServer(connectionString)
                   .UseInternalServiceProvider(serviceProvider)
                   );
             return services;
        }
    }

}

Startup:

using your.service.layer;

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

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

like image 120
Joe Audette Avatar answered Oct 17 '22 10:10

Joe Audette