我们有一个.NET Framework .dll
我们正在移植的东西.NET Core
.目前,我们继承ConfigurationElement
并ConfigurationSection
从System.Configuration
在创建自定义配置节app.config
(或者它的.NET核心当量)
问题:
它似乎是.NET Core的方式Microsoft.Extensions.Configuration
.那是对的吗?因为住在ASP.NET Core
的github上的项目,而不是.NET Core
的github上的项目.我们没有ASP部件.
如果是这样,.NET Core
创建和加载不依赖的自定义配置部分的任何示例startup.cs
?理想情况下,我们希望直接从文本源(XML或JSON)读取POCO对象图,以获得强类型的好处.
使用.NET Core 2.0,是否会支持传统,ConfigurationElement
并且ConfigurationSection
无需开始任何此类移植工作?我问的原因是.NET Core 2.0路线图说
作为此工作的一部分,.NET Core从.NET Framework获得了5,000多个API,使其成为更广泛的平台.
我不知道app.config
和System.Configuration
支持.NET Core
.可能,不,但这只是猜测.您可以.NET Core
在Main
方法中设置应用程序的配置:
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var poco = new Poco();
configuration.Bind(poco);
Console.WriteLine(poco);
Console.ReadKey();
}
}
class Poco
{
public bool Enabled { get; set; }
public Sort Sort { get; set; }
public override string ToString()
{
return $"Enabled={Enabled}, SortOrder={Sort.Order}";
}
}
class Sort
{
public int Order { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
appsettings.json
如下:
{
"enabled": true,
"sort": {
"order": 2
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Enabled=True, SortOrder=2
Run Code Online (Sandbox Code Playgroud)
您需要引用Microsoft.Extensions.Configuration.Json和Microsoft.Extensions.Configuration.Binder包.
不依赖ASP.NET Core
.
Microsoft.Extensions.Configuration
它是可扩展的,它可以使用不同的设置提供程序,如环境变量,命令行参数等.因此,ConfigurationSection
如果需要,可以实现自定义提供程序.
基于此评论,他们不会将System.Configuration引入NetStandard 2.0.
随着 .NET Standard 2.0 版本的尘埃落定,您可以使用常用的System.Configuration
即使在 Linux 上的 .NET Core 2.0 中也
这是一个测试示例:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0。这是必需的,因为元包NetStandard.Library
v2.0.0不包含此包ConfigurationSection
或ConfigurationElement
进入MyLib.dll
. 例如MyClass.cs
派生自ConfigurationSection
和MyAccount.cs
派生自ConfigurationElement
。实施细节超出了这里的范围,但谷歌是你的朋友MyApp.dll
)。.NET Core 应用程序以 Framework 结尾.dll
,而不是以.exe
Framework 结尾。app.config
使用MyApp
您的自定义配置部分创建一个。这显然应该与上面 #3 中的类设计相匹配。例如:<?xml 版本=“1.0”编码=“utf-8”?> <配置> <配置部分> <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" /> </configSections> <我的自定义配置> <我的帐户 id="007" /> </我的自定义配置> </配置>
就是这样 - 你会发现 app.config 被正确解析MyApp
,并且你现有的代码MyLib
工作得很好。dotnet restore
如果您将平台从 Windows(开发)切换到 Linux(测试),请不要忘记运行。
归档时间: |
|
查看次数: |
2353 次 |
最近记录: |