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

Passing application#39;s connection string down to a Repository Class Library in ASP.NET 5 using the IConfigurationRoot(使用 IConfigurationRoot 将应用程序的连接字符串传递到 ASP.NET 5 中的存储库类库)
本文介绍了使用 IConfigurationRoot 将应用程序的连接字符串传递到 ASP.NET 5 中的存储库类库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

IConfigurationRoot Configuration 

被设置为builder.Build();

在整个 MVC Web 应用程序中,我可以轻松完成

Throughout the MVC Web Application I can simply do

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

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

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

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

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

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

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

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

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

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

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. 创建一个新的 ASP.NET 5 MVC Web 应用.
  2. 将另一个类库(包)类型的项目添加到项目中.
  3. 想办法将 appsettings 从 ASP.NET 5 MVC 应用程序传递到类库

更新后还是看不懂.这是我的代码:

public class BaseRepo
{
    private readonly IConfigurationRoot config;

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

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

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

推荐答案

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

on your Startup.cs file add the following method

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

然后像这样更新你的 BaseRepo 类

then update your BaseRepo class like this

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)