如何从 .net core 2.0 web 应用程序的配置文件中获取 .net core 标准 class 库中的连接字符串?

How do I get a connection string in a .net core standard class library from the configuration file in a .net core 2.0 web app?

我有 .net 核心标准 class 库,它本质上是一个 DAL,具有多个 class 方法,return 从数据库中收集和对象。连接字符串位于 ASP.net 2 核心网络应用程序的 appsettings.json 文件中。我还想从控制台应用程序项目访问此 class 库,其中带有连接字符串的配置文件将出现在该控制台应用程序项目中。

这在 .net core 之前的 .net 中很简单。 DAL class 库只会从 Web 项目访问 web.config,从控制台应用程序访问 app.config,因为该库在 Web 应用程序和控制台应用程序中都被引用。但这似乎根本不可能。

我正在寻找 .net core 中的简单解决方案,以视情况从 Web 应用程序或控制台应用程序获取连接字符串。

你可能出错的地方是你想从你的 class 库访问配置,但是你想泄露关于调用者的详细信息(它会有一个 web.config ).

但是,如果您决定在 Web 应用程序中使用 Azure Key Vault 或其他机密机制怎么办?您的 class 库是否需要更改其整个实现以使用 Key Vault?那么这是否意味着您的控制台应用程序也 没有选择 只能使用 Key Vault?

所以解决方案是使用依赖倒置。简而言之,假设我有如下代码:

interface IMyRepositoryConfiguration
{
    string ConnectionString {get;}
}

class MyRepositoryConfiguration : IMyRepositoryConfiguration
{
    public string ConnectionString {get;set;}
}

class MyRepository
{
    private readonly IMyRepositoryConfiguration _myRepositoryConfiguration;

    public MyRepository(IMyRepositoryConfiguration myRepositoryConfiguration)
    {
        _myRepositoryConfiguration = myRepositoryConfiguration;
    }
}

现在在我的 startup.cs 中我可以做类似的事情:

services.AddSingleton<IMyRepositoryConfiguration>(new MyRepositoryConfiguration {//Set connection string from app settings etc});

现在我的 class 库不需要确切地知道这些配置字符串是如何存储或如何获取的。只是如果我请求 IMyRepositoryConfiguration 的一个实例,它将在其中具有值。

当然,您也可以使用选项 class,但我个人更喜欢 POCO。更多信息:https://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

很可能在 .Net 核心中轻松访问 "connection strings" 或其他配置数据,而无需太多额外的努力。

只是配置系统已经发展(变成更好的东西)&我们也必须考虑到这一点(&遵循推荐的做法)。

在您的情况下,当您访问标准库中的连接字符串值(旨在重复使用)时,您不应假设配置值将如何 "fed" 到您的 class.这意味着您不应该编写代码来直接从配置文件中读取连接字符串 - 而是依赖依赖注入机制为您提供所需的配置 - 不管它是如何提供给您的应用程序的。

一种方法是 "require" 将一个 IConfiguration 对象注入到您的 class 构造函数中,然后使用 GetValue 方法检索适当键的值,如下所示:

public class IndexModel : PageModel
{
    public IndexModel(IConfiguration config)
    {
        _config = config;
    }

    public int NumberConfig { get; private set; }

    public void OnGet()
    {
        NumberConfig = _config.GetValue<int>("NumberKey", 99);
    }
}

在 .net 核心中,在配置和启动应用程序之前,会配置并启动一个 "host"。宿主负责应用程序的启动和生命周期管理。应用程序和主机都使用各种 "configuration providers" 配置。主机配置 key-value 对成为应用程序全局配置的一部分。

按照启动时指定配置提供程序的顺序读取配置源。

.Net core支持各种"providers"。 Read this article for complete information on this topic.