假设下面的项目结构:
A计划:
- .NET完整的框架(4.6.2)
- 内部经由访问配置:
ConfigurationManager.AppSettings [ “键”];
项目B:
- 达网络核心2.0(编译到.NET 4.6.2)
- 引用并使用一个项目
问题:
达网络核心使用新的配置机制 - 是有办法的方式,将使项目甲经由ConfigurationManager中消耗配置挂钩(项目B)的.NET芯配置 - 即没有在项目A码的变化?
添加NuGet包System.Configuration.ConfigurationManager像这个答案只增加ConfigurationManager中,以项目B,但在项目中没有配置通过ConfigurationManager中可用
诀窍是使用ConfigurationManager.AppSettings.Set
方法预填充ConfigurationManager.AppSettings
从.NET这样的核心类库以后可以使用它。
我使用下列类来JSON设置加入到ConfigurationManager
。
public class CustomJsonConfigurationProvider : JsonConfigurationProvider
{
public CustomJsonConfigurationProvider(JsonConfigurationSource source) : base(source) { }
public override void Load()
{
base.Load();
foreach (string key in Data.Keys)
{
string[] keyParts = key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
ConfigurationManager.AppSettings.Set(keyParts[keyParts.Length - 1], Data[key]);
}
}
}
public class CustomJsonConfigurationSource : JsonConfigurationSource
{
public override IConfigurationProvider Build(IConfigurationBuilder builder)
{
FileProvider = FileProvider ?? builder.GetFileProvider();
return new CustomJsonConfigurationProvider(this);
}
}
public static class CustomConfiguratorExtensions
{
public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, string path)
{
return AddCustomJsonFile(builder, provider: null, path: path, optional: false, reloadOnChange: false);
}
public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, string path, bool optional)
{
return AddCustomJsonFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false);
}
public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange)
{
return AddCustomJsonFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange);
}
public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
{
if (provider == null && Path.IsPathRooted(path))
{
provider = new PhysicalFileProvider(Path.GetDirectoryName(path));
path = Path.GetFileName(path);
}
var source = new CustomJsonConfigurationSource
{
FileProvider = provider,
Path = path,
Optional = optional,
ReloadOnChange = reloadOnChange
};
builder.Add(source);
return builder;
}
}
用法:
builder.ConfigureAppConfiguration((w, c) =>
{
c.AddCustomJsonFile("appsettings.json");
});
文章来源: .Net Core 2.0 appsettings with .net full framework using ConfigurationManager