使用IConfigurationRoot传递应用程序的连接字符串到存储库类库ASP.NET 5 [英] Passing application's connection string down to a Repository Class Library in ASP.NET 5 using the IConfigurationRoot

查看:3974
本文介绍了使用IConfigurationRoot传递应用程序的连接字符串到存储库类库ASP.NET 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 5 Web应用程序,并在Startup.cs我看到公共财产

  IConfigurationRoot配置

被设置为
builder.Build();



整个MVC Web应用程序,我可以简单地做

  Startup.Configuration [数据:DefaultConnection:ConnectionString的] 

要获得康涅狄格州字符串从 appsettings.json 文件。



我怎样才能在ASP.NET MVC 5指定的连接字符串 appsettings.json 向下传递到我的仓库类库使用构造器注入



更新:结果
下面是所有其他存储库继承基础库(因为你可以看到我有一个硬编码的连接字符串这里现在):

 公共类BaseRepo 
{
公共静态字符串的ConnectionString =服务器= MYSERVER;数据库= MYDATABASE; Trusted_Connection = TRUE;;

公共静态的SqlConnection GetOpenConnection()
{
变种CS = ConnectionString的;
VAR连接=新的SqlConnection(CS);
connection.Open();
返回连接;
}
}

在我的AppSettings我的asp.net 5 Web应用程序以.json文件我有这相当于在.NET添加一个连接字符串一个web.config 4.5 Web应用程序如下:

 数据:{
DefaultConnection:{
的ConnectionString:服务器= MYSERVER;数据库= MYDATABASE; Trusted_Connection = TRUE;
}
}

此外在我的asp.net 5 web应用程序我有在我Startup.cs下面的默认代码,加载网站配置成类型IConfigurationRoot的公共属性:

 公共IConfigurationRoot配置{得到;组; } 
//类的构造函数
公共启动(IHostingEnvironment ENV)
{
//设置配置源。
变种建设者=新ConfigurationBuilder()
.AddJsonFile(appsettings.json)
.AddJsonFile($的AppSettings {} env.EnvironmentName以.json,可选的:真正的);

如果(env.IsDevelopment())
{
//有关使用用户秘专卖店看到http://go.microsoft.com/fwlink/更多的细节?链路ID = 532709
builder.AddUserSecrets();
}

builder.AddEnvironmentVariables();
配置= builder.Build();
}

在我的asp.net web应用程序现在,如果我想访问任何在AppSettings的我可以简单的做到以下几点: Startup.Configuration [数据:DefaultConnection:ConnectionString的]



不过,不幸的是我无法从我的类库做到这一点。



如果有人想尝试,并想出解决办法是在这里重现步骤:




  1. 创建一个新的ASP.NET MVC 5 Web应用程序。

  2. 类型类库(包)的另一个项目添加到项目中。

  3. 想出一个办法,从ASP.NET MVC 5应用传递的AppSettings的类库



更新我仍然不能完全得到它后。这里是我的代码:



 公共类BaseRepo 
{
私人只读IConfigurationRoot配置;

公共BaseRepo(IConfigurationRoot配置)
{
this.config =配置;
}
}



此类声明没有因为BaseRepo工作需要一个构造函数参数现在

 公共类CustomerRepo:BaseRepository,ICustomerRepo 
{
公众客户查找(INT ID)
{使用
(VAR连接= GetOpenConnection())
{

}
}
}


解决方案

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

 公共无效ConfigureServices(IServiceCollection服务){
services.AddSingleton(_ =>配置);
}



然后更新您的BaseRepo类像这样

 公共类BaseRepo {
私人只读IConfigurationRoot配置;

公共BaseRepo(IConfigurationRoot配置){
this.config =配置;
}

公共静态的SqlConnection GetOpenConnection(){
变种CS = config.Get<串GT;(数据:DefaultConnection:ConnectionString的);
VAR连接=新的SqlConnection(CS);
connection.Open();
返回连接;
}
}


I have an ASP.NET 5 MVC Web Application and in Startup.cs I see that the public property

IConfigurationRoot Configuration 

is being set to builder.Build();

Throughout the MVC Web Application I can simply do

Startup.Configuration["Data:DefaultConnection:ConnectionString"]

to get the conn string from the appsettings.json file.

How can I get the connection string specified in the ASP.NET 5 MVC appsettings.json passed down to my Repository Class Library using constructor injection?

UPDATE:
Here is the base repository that all other repositories inherit from (as you can see I have a hardcoded connection string in here for now):

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;
    }
}

In my asp.net 5 web application in my appsettings.json file I have the following which is equivalent to adding a connection string to a web.config in a .net 4.5 webapp:

  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;"
    }
  }

Additionally in my asp.net 5 web application I have the following default code in my Startup.cs which loads the sites configuration into a public property of type 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();
        }

Now in my asp.net web application if I would like to access any of the appsettings I can simple do the following: Startup.Configuration["Data:DefaultConnection:ConnectionString"]

But unfortunately I can't do this from my class library..

If someone wants to try and figure this out here are the steps to reproduce:

  1. Create a new ASP.NET 5 MVC Web App.
  2. Add another project of type Class Library (Package) to the project.
  3. Figure out a way to pass appsettings from the ASP.NET 5 MVC App to the Class Library

After updating I still can't quite get it. Here is my code:

public class BaseRepo
{
    private readonly IConfigurationRoot config;

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

This class declaration does not work since BaseRepo requires a constructor param now.

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

解决方案

on your Startup.cs file add the following method

public void ConfigureServices(IServiceCollection services) {
    services.AddSingleton(_ => Configuration);
}

then update your BaseRepo class like this

public class BaseRepo {
    private readonly IConfigurationRoot config;

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

    public static SqlConnection GetOpenConnection() {
        var cs = config.Get<string>("Data:DefaultConnection:ConnectionString");
        var connection = new SqlConnection(cs);
        connection.Open();
        return connection;
    }
}

这篇关于使用IConfigurationRoot传递应用程序的连接字符串到存储库类库ASP.NET 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆