asp.net-mvc - 在不使用 EF 的情况下在 appsettings.json 中获取多个连接字符串

标签 asp.net-mvc asp.net-core asp.net-core-mvc dapper

刚刚通过迁移我开发的当前 MVC .Net 应用程序开始使用 .Net Core RC2。在我看来,由于 appsettings.json 处理配置的方式,如果我有多个连接字符串,我要么必须使用 EF 检索连接字符串,要么必须创建为每个连接字符串命名的单独类。我看到的所有示例要么使用 EF(这对我来说没有意义,因为我将使用 Dapper),要么该示例构建一个以配置中的部分命名的类。我是否缺少更好的解决方案?

    "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 (一旦您指定了强类型配置对象并将其添加到服务集合中,您就可以请求它通过请求 IOptions 实例从任何 Controller 或操作方法, https://docs.asp.net/en/latest/mvc/controllers/dependency-injection.html )

所以这会发送到 Controller ,

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

然后当您实例化 DAL 时,您将传递适当的连接字符串

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

所有示例都表明了这一点,但他们只是没有说明,为什么我尝试直接从 DAL 提取数据不起作用

关于asp.net-mvc - 在不使用 EF 的情况下在 appsettings.json 中获取多个连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287427/

相关文章:

asp.net - 注册时Chrome保存的是电话号码而不是电子邮件

c# - asp.net core ControllerBase.User 没有实现 Controller

c# - 是否可以配置从 Nginx 到 kestrel aspnet core 的 kerberos 转发

javascript - 在 data-ajax-success 调用中以编程方式在 ValidationSummary 中添加错误

c# - 制作 Saas MVC 应用程序...需要客户特定的 View 、资源文件和逻辑

c# - 是否可以使用所有记录或匹配 id 方法从数据库中检索记录?

ASP.NET MVC : How to send an html email using a controller?

asp.net-core - ASP.NET Core 添加 View 参数名称路径不能为空错误

javascript - 将外部js文件导入到另一个外部js文件中

asp.net-core-mvc - 重新启动 asp.net MVC 6 应用程序