相关疑难解决方法(0)

使用IConfigurationRoot将应用程序的连接字符串传递到ASP.NET 5中的存储库类库

我有一个ASP.NET 5 MVC Web应用程序,在Startup.cs中我看到了公共属性

IConfigurationRoot Configuration 
Run Code Online (Sandbox Code Playgroud)

正在设定 builder.Build();

在整个MVC Web应用程序中,我可以做到

Startup.Configuration["Data:DefaultConnection:ConnectionString"]
Run Code Online (Sandbox Code Playgroud)

appsettings.json文件中获取conn字符串.

如何appsettings.json使用构造函数注入将ASP.NET 5 MVC中指定的连接字符串传递到我的存储库类库?

更新:
这是所有其他存储库继承的基本存储库(如您所见,我现在在这里有一个硬编码连接字符串):

public class BaseRepo
{
    public static string ConnectionString = "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;";

    public static SqlConnection GetOpenConnection()
    {
        var cs = ConnectionString;
        var connection = new SqlConnection(cs);
        connection.Open();
        return connection;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的appsettings.json文件中的asp.net 5 Web应用程序中,我有以下内容,相当于将连接字符串添加到.net 4.5 webapp中的web.config:

  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;"
    }
  }
Run Code Online (Sandbox Code Playgroud)

另外在我的asp.net 5 Web应用程序中,我的Startup.cs中有以下默认代码,它将站点配置加载到IConfigurationRoot类型的公共属性中:

 public IConfigurationRoot Configuration { get; set; }
// Class Constructor
        public Startup(IHostingEnvironment env)
        { …
Run Code Online (Sandbox Code Playgroud)

c# configuration asp.net-core-mvc asp.net-core

24
推荐指数
2
解决办法
3万
查看次数

在mvc6中全局使用IConfiguration

我可能已经长时间盯着这个了,但是最近几天我已经跳进了MVC6 for asp.net,而我真的很享受这个,我似乎无法找到一个方便的方法来访问它之后的配置在Start.cs中定义

Configuration = new Configuration()
    .AddJsonFile("config.json")
    ...
Run Code Online (Sandbox Code Playgroud)

那么,我需要将它添加到DI中还是已经存在?或者我应该在需要使用它时创建一个新实例,因为可以创建不同的配置(例如IIdentityMessageService)创建sendgrid.json并在Service本身中加载它?

可能有一个非常简单的解决方案,但就像我说我已经看了好几天了.

configuration asp.net-core

11
推荐指数
1
解决办法
3688
查看次数