Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is UseConsoleLifetime included by default in .NET Generic Host (Host.CreateDefaultBuilder)?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the Microsoft docs:

>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.ConsoleLifetime is the default IHostLifetime implementation.

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading