来自带有实体框架核心的数据层中 appsettings.json 的 ConnectionString [英] ConnectionString from appsettings.json in Data Tier with Entity Framework Core

查看:31
本文介绍了来自带有实体框架核心的数据层中 appsettings.json 的 ConnectionString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Entity Framework Core 在 ASP.NET Core 上构建的新应用程序.该应用程序具有 UI、模型、业务和数据层.在以前版本的 ASP.NET 中,您可以在 web.config 中设置连接字符串,默认情况下它会在引用的层中可用.这在 ASP.NET Core 中与 appsettings.json(或其他配置选项)似乎不同?关于这是如何实现的任何想法?我在数据层配置了 dbcontext,但我目前正在硬编码连接字符串.

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.

我看到的所有示例都在 startup.cs 的 UI 层中配置了 dbcontext.这是我试图避免的.

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.

问题这里跑题了.

推荐答案

您可以轻松地将 IServiceCollection 的扩展方法添加到您的业务/服务层,并使用它来注册自己的依赖项.然后在启动时,您只需调用服务层上的方法,而无需在您的网络应用中引用 EntityFramework.

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

}

启动:

using your.service.layer;

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

现在您的网络应用只需要对您的业务/服务层的引用,而不直接依赖于 EntityFramework.

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

这篇关于来自带有实体框架核心的数据层中 appsettings.json 的 ConnectionString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆