I initially configured my Console application using .NET generic host as follows:
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddLogging();
})
.ConfigureLogging((hostContext, configLogging) =>
{
configLogging.AddConsole();
})
.UseConsoleLifetime()
.Build();
await builder.RunAsync();
Then I realized I also needed appsettings.json and appsettings.{Environment}.json, which led me to the decision to use Host.CreateDefaultBuilder, as it includes the default logging, appsettings, and some other defaults:
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
})
.UseConsoleLifetime() // Is this line necessary?
.Build();
Now I wonder if UseConsoleLifetime is actually included in the default builder. I wasn’t able to find it by decompiling several source code files, but just to be sure, I decided to ask this question.
Here is the Microsoft docs:
- https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host?tabs=hostbuilder
- https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host?tabs=appbuilder#host-shutdown
>Solution :
Yes, it is. The only thing UseConsoleLifetime actually does is that it registers ConsoleLifetime as IHostLifetime. And ConsoleLifetime is the default one. From the generic hosting docs:
Microsoft.Extensions.Hosting.Internal.ConsoleLifetimeis the defaultIHostLifetimeimplementation.
And it is easy to check it out:
var builder = Host.CreateDefaultBuilder();
var build = builder.Build();
Console.WriteLine(build.Services.GetService<IHostLifetime>() is ConsoleLifetime); // prints "True"
If you wonder where the lifetime is set by default – see the AddLifetime call in the HostBuilder.PopulateServiceCollection which is called both by HostBuilder itself (i.e. Host.CreateDefaultBuilder) and HostApplicationBuilder (i.e. Host.CreateApplicationBuilder()).
Also consider using Host.CreateApplicationBuilder() since it seems more in line with approach to setting up the application.