我正在将 .netframework 4.7.2 类库迁移到 .netstandard 2.0 类库。
在 .netframework 类库中使用 ConfigurationManager 读取应用程序设置。
.netstandard 中是否有 System.Configuration.ConfigurationManager 的替代选项。
迁移后的类库需要在 .net core web API 和旧版 .netframework web 应用程序中使用。
我正在将 .netframework 4.7.2 类库迁移到 .netstandard 2.0 类库。
在 .netframework 类库中使用 ConfigurationManager 读取应用程序设置。
.netstandard 中是否有 System.Configuration.ConfigurationManager 的替代选项。
迁移后的类库需要在 .net core web API 和旧版 .netframework web 应用程序中使用。
您可以通过NuGet软件包来安装 ConfigurationManager
,它适用于 .Net Standard 2.0。
对于ASP.Net Core,请查看Microsoft.Extensions.Configuration。
正如我所说,你不应该直接依赖于类库中获取配置的方式。保持你的类库的灵活性。
在你的类库中不要这样做:
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 });
}
}
如果在您的类库中直接使用ConfigurationManager,那么您就将该类与只允许一种获取连接字符串的方式绑定在了一起。这意味着,如果您想使用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 });
}
}
string connectionString = Configuration.GetConnectionString("MyDatabase");
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");
同时,它仍然允许您在 .NET Framework 应用程序中使用 System.Configuration,具有灵活性:
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");
感谢这个答案:https://dev59.com/pVYM5IYBdhLWcg3wlQwi#54259119
如果您检查调用ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)的结果;
我在一个 .Net 5 Web 项目中添加了 ProjName.dll.config,这使得 NetStandard2.0 项目能够从 ConfigurationManager.ConnectionStrings["x"] 和 ConfigurationManager.AppSettings["y"] 获取配置值。
虽然这显然不是开发新代码的正确方式,但这使我们能够进行大规模的 .Net Framework 迁移到 .Net 6。