在您的 Program.cs 中存储 private static IServiceProvider provider;。然后像在 aps.net core 中一样设置配置,当然你可以在 Main() 中进行。然后在您的 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>