Currently, 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.
Wouldn't it be just as valid to add .ConfigureHostConfiguration(... though?
@glennc
@slang25 In most of my cases the default host and app providers are fine so I rarely find myself tweaking them. Happy with adding the call in rarer cases.
It's the binding to typed classes and IOptions that we would do in every app. When I first used the template it took me a moment to remember the other overload was available to get at the IConfiguration. My gut is many others may struggle to work that out. Having the Bodybuilder context there supports discovery and may save a docs search for some.
My bad, I meant .ConfigureAppConfiguration(... 🤦♂️.
In my travels I've seen app builders done a number of ways, it seems to me like the template should be nonprescriptive, adding the parameter doesn't make the configuration part more discoverable than ConfigureAppConfiguration, they are both "one dot away" if that makes sense. The docs do cover the convenience methods.
I like the original suggestion, we should do this. It makes it easy to do environment checks etc.
@davidfowl PR in.
Most helpful comment
I like the original suggestion, we should do this. It makes it easy to do environment checks etc.