加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在没有EF的情况下在appsettings.json中获取多个

发布时间:2020-12-16 04:05:09 所属栏目:asp.Net 来源:网络整理
导读:通过迁移我开发的当前MVC .Net应用程序,开始玩.Net Core RC2.它看起来像我,因为使用appsettings.json处理配置的方式,如果我有多个连接字符串,我要么必须使用EF来检索连接字符串,要么我必须为每个连接字符串创建单独的类.我看到的所有示例都使用EF(这对我来说
通过迁移我开发的当前MVC .Net应用程序,开始玩.Net Core RC2.它看起来像我,因为使用appsettings.json处理配置的方式,如果我有多个连接字符串,我要么必须使用EF来检索连接字符串,要么我必须为每个连接字符串创建单独的类.我看到的所有示例都使用EF(这对我来说没有意义,因为我将使用Dapper)或者该示例构建了一个以config中的部分命名的类.我错过了更好的解决方案吗?
"Data": {
        "Server1": {
          "ConnectionString": "data source={server1};initial catalog=master;integrated security=True;"
        },"Server2": {
          "ConnectionString": "data source={server2};initial catalog=master;integrated security=True;"
        }
    }

为什么我要构建两个类,一个名为“Server1”,另一个名为“Server2”,如果唯一的属性是连接字符串?

解决方法

我对Adem对RC2工作的回应做了一些修正,所以我想我最好发布它们.

我配置了appsettings.json并创建了一个类似Adem的类

{
    "ConnectionStrings": {
      "DefaultConnectionString": "Default","CustomConnectionString": "Custom"
    }
}

public class ConnectionStrings
{
    public string DefaultConnectionString { get; set; }

    public string CustomConnectionString { get; set; }
}

大多数Adem的代码都是在VS for RC2中开箱即用的,所以我只是将下面的行添加到了ConfigureServices方法中

services.Configure<Models.ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

主要的缺点是必须将连接字符串传递给控制器??(一旦您指定了强类型配置对象并将其添加到服务集合,您可以通过请求实例从任何Controller或Action方法请求它IOptions,https://docs.asp.net/en/latest/mvc/controllers/dependency-injection.html)

所以这是控制器,

private readonly ConnectionStrings _connectionStrings;
        public HomeController(IOptions<ConnectionStrings> connectionStrings)
        {
            _connectionStrings = connectionStrings.Value;
        }

然后在实例化DAL时传递相应的connectionString

DAL.DataMethods dm = new DAL.DataMethods(_connectionStrings.CustomConnectionString);

所有的例子都说明了这一点,他们只是没有说明,为什么我试图直接从DAL拉出来不起作用

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读