IOptions的.NET Core 3 Worker服务依赖项注入配置

时间:2019-10-29 14:38:15

标签: c# dependency-injection .net-core backgroundworker

我有一个有关DI的问题,下面回答了另一个帖子。

.NET Core 3 Worker Service Settings Dependency Injection

如果我想添加一些帮助程序类并进行如下注册,该怎么办。 我如何使用该选项注入。 因为我想我错过了一些东西...

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类具有一个类似Worker的构造函数。

public static MySettings _configuration { get; set; }

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

1 个答案:

答案 0 :(得分:1)

无需自行构建配置。您可以通过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>(); 
        });
}

现在只需将选项注入所需的帮助器类中

//...

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

//...

和工人服务

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