通过 IOptions 配置 .NET Core 3 Worker 服务依赖注入

.NET Core 3 Worker Service Dependency Injection Configuration by IOptions

我有一个关于 DI on Worker Service 的问题,在下面回答了另一个 post。

如果我想添加一些助手 class 并按如下方式注册怎么办? 我如何使用该选项注入。 因为我想,我错过了一些东西...

public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)

            .ConfigureAppConfiguration((hostContext, config) =>
            {
                // Configure the app here.
                config
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);

                config.AddEnvironmentVariables();

                Configuration = config.Build();

            })

            .ConfigureServices((hostContext, services) =>
            {

                services.AddOptions();               

                services.Configure<MySettings>(Configuration.GetSection("MySettings"));                    


                services.AddSingleton<RedisHelper>();

                services.AddHostedService<Worker>();                   

            });
    }

RedisHelper class 有一个像这样的构造函数作为 Worker。

public static MySettings _configuration { get; set; }

public RedisHelper(IOptions<MySettings> configuration)
{
    if (configuration != null)
        _configuration = configuration.Value;
}

无需自己构建配置。您可以通过 hostContext

在 ConfigureServices 中访问它
public static IHostBuilder CreateHostBuilder(string[] args) {
    return Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostContext, config) => {
            // Configure the app here.
            config
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);

            config.AddEnvironmentVariables();
        })
        .ConfigureServices((hostContext, services) => {

            services.AddOptions();               

            services.Configure<MySettings>(hostContext.Configuration.GetSection("MySettings"));
            services.AddSingleton<RedisHelper>();
            services.AddHostedService<Worker>(); 
        });
}

现在只需将选项注入所需的助手即可 class

//...

public RedisHelper(IOptions<MySettings> configuration) {
    if (configuration != null)
        _configuration = configuration.Value;
}

//...

和 Worker 服务

public Worker(RedisHelper helper) {
    this.helper = helper;
}