ConnectionString from appsettings.json in the data core with the Entity Framework core database

I have a new application that I based on the ASP.NET core with the Entity Framework core. The application has a user interface, model, business and data layer. In previous versions of ASP.NET, you could set the connection string in the web.config file, and by default it will be available at reference levels. Is this not like the same case in ASP.NET Core with appsettings.json (or other configuration options)? Any idea on how this is done? I have a dbcontext configured in the data layer, but I am currently hardcoded the connection string.

All the examples that I see there have dbcontext configured at the user interface level in startup.cs. This is what I am trying to avoid.

Question Here out of topic.

+1
source share
1 answer

You can easily add the IServiceCollection extension method to your business / service level and use it to register your dependencies. Then, during the startup process, you call the method at the service level without reference to the EntityFramework in your web application.

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 application only needs a link to your business / service level, and it does not depend directly on EntityFramework.

+7
source

Source: https://habr.com/ru/post/1247838/


All Articles