i have a question about DI on Worker Service that answered another post below.
.NET Core 3 Worker Service Settings Dependency Injection
what if i want to add some helper class and registered as below. How can i use that option injection. because i think, i missed something...
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 has a constructor like this as Worker.
public static MySettings _configuration { get; set; }
public RedisHelper(IOptions<MySettings> configuration)
{
if (configuration != null)
_configuration = configuration.Value;
}
No need to build the config yourself. You can access it in the ConfigureServices via the 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>();
});
}
Now it is just a matter of injecting the options into the desired helper class
//...
public RedisHelper(IOptions<MySettings> configuration) {
if (configuration != null)
_configuration = configuration.Value;
}
//...
and the Worker service
public Worker(RedisHelper helper) {
this.helper = helper;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With