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

Bla*_*ell 24 c# configuration asp.net-core-mvc asp.net-core

我有一个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)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }
Run Code Online (Sandbox Code Playgroud)

现在在我的asp.net Web应用程序中,如果我想访问任何appsettings,我可以简单地执行以下操作: Startup.Configuration["Data:DefaultConnection:ConnectionString"]

但不幸的是,我不能从我的班级图书馆做到这一点..

如果有人想尝试解决这个问题,那么重现的步骤如下:

  1. 创建一个新的ASP.NET 5 MVC Web App.
  2. 将类库(包)类型的另一个项目添加到项目中.
  3. 找出将appsettings从ASP.NET 5 MVC App传递到类库的方法

更新后我仍然无法得到它.这是我的代码:

public class BaseRepo
{
    private readonly IConfigurationRoot config;

    public BaseRepo(IConfigurationRoot config)
    {
        this.config = config;
    }
}
Run Code Online (Sandbox Code Playgroud)

此类声明不起作用,因为BaseRepo现在需要构造函数参数.

public class CustomerRepo : BaseRepository, ICustomerRepo
{
    public Customer Find(int id)
    {
        using (var connection = GetOpenConnection())
        {
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Man*_*nis 29

在您的Startup.cs文件中添加以下方法

public void ConfigureServices(IServiceCollection services) {
    services.AddSingleton(_ => Configuration);
}
Run Code Online (Sandbox Code Playgroud)

然后像这样更新你的BaseRepo类

public class BaseRepo {
    private readonly IConfiguration config;

    public BaseRepo(IConfiguration config) {
        this.config = config;
    }

    public SqlConnection GetOpenConnection() {
        string cs = config["Data:DefaultConnection:ConnectionString"];
        SqlConnection connection = new SqlConnection(cs);
        connection.Open();
        return connection;
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ono 13

ASP.NET提供了自己的传递配置设置的方法.

假设你在appSettings.json中有这个:

{
  "Config": {
    "Setting1": 1,
    "Setting2": "SO"
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你需要一个这样的类:

public class MyConfiguration
{
    public int Setting1 { get; set; }

    public string Setting2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这允许您通过添加以下行来使用此配置配置服务

services.Configure<MyConfigurationDto>(Configuration.GetSection("Config"));
Run Code Online (Sandbox Code Playgroud)

ConfigureServices.

然后,您可以通过执行以下操作在构造函数中注入配置:

public class SomeController : Controller
{
    private readonly IOptions<MyConfiguration> config;

    public ServiceLocatorController(IOptions<MyConfiguration> config)
    {
        this.config = config;
    }

    [HttpGet]
    public IActionResult Get()
    {
        return new HttpOkObjectResult(config.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

此示例适用于控制器.但是您可以对应用程序的其他层执行相同的操作.