简体   繁体   English

NET 6:具有强类型配置的 Windows 服务

[英]NET 6: Windows Service with strongly typed configuration

I'm trying to create a Windows Service using NET 6 and documentation found here .我正在尝试使用 NET 6 和此处找到的文档创建 Windows 服务。

I'd like to use strongly typed configuration pattern, so I modified startup code this way:我想使用强类型配置模式,所以我这样修改了启动代码:

using IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "My Service";
    })
    .ConfigureAppConfiguration((hostingContext, configuration) =>
    {
        configuration.Sources.Clear();
        IHostEnvironment env = hostingContext.HostingEnvironment;

        configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    })
    .ConfigureServices((hostingContext, services) =>
    {
        services.AddSingleton<MyService>();
        services.Configure<AppSettings>(hostingContext.Configuration.GetSection("AppSettings"));
        services.AddHostedService<WindowsBackgroundService>();
    })
    .Build();

await host.RunAsync();

Then in MyService.cs:然后在 MyService.cs 中:

private AppSettings _appSettings;

public MyClass(AppSettings appSettings)
{
    _appSettings = appSettings;
}

This gives me the following exception:这给了我以下例外:

System.InvalidOperationException: 'Unable to resolve service for type 'StatSveglia.Service.AppSettings' while attempting to activate 'StatSveglia.Service.SvegliaService'.' System.InvalidOperationException:“尝试激活“StatSveglia.Service.SvegliaService”时,无法解析“StatSveglia.Service.AppSettings”类型的服务。”

It seems that this line has no effect:这条线似乎没有效果:

services.Configure<AppSettings>(hostingContext.Configuration.GetSection("AppSettings"));

How should I change my code to use configuration injection?我应该如何更改我的代码以使用配置注入?

A side question: in the example service found in documentation, services.AddHttpClient<JokeService>();一个附带问题:在文档中找到的示例服务中, services.AddHttpClient<JokeService>(); is used to add the service.用于添加服务。 My service is not an HTTP client, so I preferred .AddSingleton<> .我的服务不是 HTTP 客户端,所以我更喜欢.AddSingleton<> Is this a good choice?这是一个不错的选择吗?

After further reading I found out that the line:进一步阅读后,我发现该行:

services.Configure<AppSettings>(hostingContext.Configuration.GetSection("AppSettings"));

registers for dependency injection the class IOptions<AppSettings> and not AppSettings itself.为依赖注入注册 class IOptions<AppSettings>而不是AppSettings本身。

The correct use is therfore:因此正确的用法是:

private IOptions<AppSettings> _appSettings;

public MyClass(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

private void SomeMethod()
{
    var mySetting = _appSettings.Value.MySetting
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM