簡體   English   中英

如何在 .netstanard 庫中為 .net 核心和 .netframework 使用 System.Configuration.ConfigurationManager

[英]How to use System.Configuration.ConfigurationManager in .netstanard library for .net core and .netframework

我正在將 .netframework 4.7.2 class 庫遷移到 .netstandard 2.0 庫。

ConfigurationManager 在 .netframework class 庫中用於讀取應用程序設置。

.netstanard 中的 System.Configuration.ConfigurationManager 可用的任何替代選項。

The migrated class library needs to be used in a .net core web API and old .netframework web application.

您可以通過nuget package安裝ConfigurationManager ,它針對.Net Standard 2.0。

至於 ASP.Net Core,請查看Microsoft.Extensions.Configuration

正如我所說,您不應該直接依賴如何在 class 庫中獲取配置。 保持 class 庫的靈活性。

不要在您的 class 庫中執行此操作:

public void UpdateProductName(int productId, string name)
{
    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"]))
    {
        connection.ExecuteNonQuery("UPDATE dbo.Products SET Name = @Name WHERE Id = @ProductId", new {  ProductId = productId, Name = name });
    }
}

通過在 class 庫中直接使用 ConfigurationManager,您已將 class 綁定到僅允許一種形式的獲取連接字符串。 這意味着,如果您想使用 appsettings.json、環境變量、KeyVault 或任何其他獲取配置的方法,則不能。

相反,請執行以下操作:

public class MyDatabaseRepository
{
    readonly string _connectionString;

    public MyDatabaseRepository(string connectionString)
    {
        _connectionString = connectionString;
    }
} 

public void UpdateProductName(int productId, string name)
{
    using (var connection = new SqlConnection(_connectionString))
    {
        connection.ExecuteNonQuery("UPDATE dbo.Products SET Name = @Name WHERE Id = @ProductId", new {  ProductId = productId, Name = name });
    }
}

現在,這允許您在使用應用程序中獲取所需的連接字符串。

在 .NET 核心應用程序中,您可以通過 Microsoft.Extensions.Configuration 從 appsettings.json 獲取連接字符串:

string connectionString = Configuration.GetConnectionString("MyDatabase");
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");

它仍然允許您在 .NET 框架應用程序中靈活地使用 System.Configuration:

string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");

再加上依賴注入,這成為一個非常靈活和強大的工具。

感謝這個答案: https://stackoverflow.com/a/54259119/672110

如果您檢查對 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 的調用結果;

我將 ProjName.dll.config 添加到 a.Net 5 Web 項目中,這允許 NetStandard2.0 項目從 ConfigurationManager.ConnectionStrings["x"] 和 ConfigurationManager.AppSettings["y"] 獲取配置值

雖然這顯然是開發新代碼的錯誤方式,但這讓我們能夠繼續將大型 .Net 框架遷移到 .Net 6。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM