Конфигурация внедрения зависимостей рабочих служб .NET Core 3 с помощью операций ввода-вывода - PullRequest
2 голосов
/ 29 октября 2019

У меня есть вопрос о DI на Worker Service, который ответил на другой пост ниже.

.NET Core 3 Worker Service Settings Внедрение зависимостей

что делать, если я хочу добавить некоторый вспомогательный класс и зарегистрирован, как показано ниже. Как я могу использовать этот вариант инъекции. потому что я думаю, я что-то упустил ...

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 Ответ

1 голос
/ 29 октября 2019

Не нужно собирать конфиг самостоятельно. Вы можете получить к нему доступ в ConfigureServices через hostContext

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;
}

//...

и службу Worker *. 1008 *

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