Bra*_*ord 22 .net asp.net asp.net-core
我有一个类库,我正在转换为.Net Standard 2类库,以便在ASP.Net Core 2.0项目中使用.
该库始终从配置文件中读取诸如SMTP设置,连接字符串等项.
在Web项目中,它在web.config中找到这些值.
在Console/WinForms中,它在app.config中找到这些值.
是否存在.Net Core 2.0项目的等效配置文件,与之前的示例一样"正常工作"?
我假设答案是否定的,但是考虑到整个组织使用库,寻找最佳处理方法,因此保持向后兼容性非常重要.
Bra*_*ord 33
结果是System.Configuration.ConfigurationManager在.NETStandard 2.0中被添加回来了.
只需从nuget中获取它并编译.NETStandard 2.0类库项目.
然后,该库将使用标准配置文件跨项目工作:
.Net Core大大修改了配置方法。
ConfigurationManager.AppSettings["someSetting"]每当您需要某些设置值时,您就不再打电话。而是在启动应用程序时使用加载配置ConfigurationBuilder。可能有多个配置源(json或/和xml配置文件,环境变量,命令行,Azure Key Vault等)。
然后,您将构建配置并将包装好的强类型设置对象传递IOption<T>给使用类。
这是其工作原理的基本思想:
// Application boostrapping
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json");
var configuration = configurationBuilder.Build();
// IServiceCollection services
services.AddOptions();
services.Configure<SomeSettings>(configuration.GetSection("SomeSection"));
// Strongly typed settings
public class SomeSettings
{
public string SomeHost { get; set; }
public int SomePort { get; set; }
}
// Settings consumer
public class SomeClient : ISomeClient
{
public SomeClient(IOptions<SomeSettings> someSettings)
{
var host = someSettings.Value.SomeHost;
var port = someSettings.Value.SomePort;
}
}
// AppSettings.json
{
"SomeSection": {
"SomeHost": "localhost",
"SomePort": 25
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅文章“ 配置ASP.NET Core应用程序”。
恐怕很难保持向后兼容性(试图避免“不可能”一词)。
| 归档时间: |
|
| 查看次数: |
11705 次 |
| 最近记录: |