Worker Template Suggestion - Use Different ConfigureServices Overload by Default
See original GitHub issueCurrently, when using the new Worker template, it includes a call to ConfigureServices to add the hosted service.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
});
A common requirement I have for worker services is that we will have some configuration which we want to bind for use from IOptions.
To support this, I have to change to the overload of ConfigureServices which accepts Action<HostBuilderContext, IServiceCollection>
so that I can access the Configuration from there.
For example:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.Configure<MySettings>(hostContext.Configuration.GetSection("MySettings"));
services.AddHostedService<Worker>();
});
Since this is likely to be a common need, I would propose that perhaps the template should include that overload by default:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
I would assume that this may help guide developers towards this path for the scenario where they need to bind configuration which in my experience would be the vast majority of the workers we have.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:6 (6 by maintainers)
I like the original suggestion, we should do this. It makes it easy to do environment checks etc.
@davidfowl PR in.