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

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

问题描述

我有一个使用Entity Framework Core在ASP.NET Core上构建的新应用程序.该应用程序具有UI,模型,业务和数据层.在ASP.NET的早期版本中,您可以在web.config中设置连接字符串,默认情况下,该字符串将在引用层中可用.在带有appsettings.json(或其他配置选项)的ASP.NET Core中,情况似乎并不相同?关于如何实现的任何想法?我已经在数据层中配置了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的扩展方法添加到您的业务/服务层中,并使用它来注册自己的依赖项.然后,在启动过程中,您只需在服务层上调用方法,而无需在Web应用程序中引用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);
}

现在,您的Web应用程序仅需要引用您的业务/服务层,而不再直接依赖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天全站免登陆