在Program.cs中存储一个
private static IServiceProvider provider;
,然后在Main()方法中设置配置,就像您在aps.net core中一样。然后在IServiceProvider内部配置每个部分,这样您就可以使用构造函数依赖项注入。还请注意,我的示例中有两个配置。其中一个包含应从源代码控制中排除并存储在项目结构之外的机密信息,而另一个是包含不需要保密的标准配置设置的AppSettings。(这很重要!) 当您想要使用配置时,您可以将其从提供程序中取出,或从使用设置类的对象中的构造函数获取提供程序中的对象。
private static IServiceProvider provider;
private static EventReceiver receiver;
static void Main(string[] args)
{
IConfigurationRoot config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "/opt/Secrets.json", optional: false, reloadOnChange: true)
.AddJsonFile(path: "AppSettings.json", optional: false, reloadOnChange: true)
.Build();
provider = new ServiceCollection()
.AddSingleton<CancellationTokenSource>()
.Configure<Settings>(config.GetSection("SettingsSection"))
.BuildServiceProvider();
receiver = new EventReceiver<Poco>(ProcessPoco);
provider.GetRequiredService<CancellationTokenSource>().Token.WaitHandle.WaitOne();
}
private static void ProcessPoco(Poco poco)
{
IOptionsSnapshot<Settings> settings = provider.GetRequiredService<IOptionsSnapshot<Settings>>();
Console.WriteLine(settings.ToString());
}
这些是我在创建 dotnetcore cli 应用程序时建议开始使用的依赖项。
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="microsoft.extensions.logging.abstractions" Version="2.0.0" />
请注意,您需要将设置复制到发布和构建目录中。您可以通过向csproj文件添加目标来实现。
<Target Name="CopyToOut" BeforeTargets="BeforeBuild">
<Copy SourceFiles="../ProjPath/AppSettings.json" DestinationFolder="$(TargetDir)" SkipUnchangedFiles="true" />
</Target>
<Target Name="CopyToOutOnPublish" AfterTargets="Publish">DestinationFolder="$(PublishDir)" SkipUnchangedFiles="true" />
<Copy SourceFiles="../ProjPath/AppSettings.json" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="true" />
</Target>
Microsoft.Extensions.Configuration
是一个独立的软件包。虽然它由ASP.NET团队维护,但它不依赖于ASP.NET。您可以在任何.NET Standard平台上使用ConfigurationBuilder
。 - Jeroen Mostert