17

We generally Create Host using the Host.CreateDefaultBuilder() Method. The Host.CreateDefaultBuilder returns an IHostBuilder. The IHostBuilder has some extension methods by which we can configure the builder. After configuring the IHostBuilder We build the IHost by IHostBuilder.Build().

But on .NET Platform Extension 7, a new method is introduced Host.CreateApplicationBuilder(). It gives us an HostApplicationBuilder instance. It doesn't have extension methods like IHostBuilder to configure, but it has some properties such as Configuration, Environment, Logging, Services, etc. And using HostApplicationBuilder.Build() we can eventually Build the IHost.

My question is when and why we should build Host using the HostApplicationBuilder instead of IHostBuilder? And how to configure srvices, configurations, etc on HostApplicationBuilder, do we need to directly use its properties(Configuration, Environment, Logging, Services, etc)?

I tried searching on google but got no answer.

S.Nakib
  • 463
  • 7
  • 10
  • 1
    There's a bit of documentation about this "improvement" here... https://github.com/dotnet/runtime/issues/61634 – KrisG Feb 08 '23 at 22:58

1 Answers1

7

It is documented a bit here and here.

The general idea was to move away from calbacks and move to linear code for configuring everything

Code samples from the link...

Web

var builder = WebApplication.CreateBuilder();

builder.Logging.AddConsole();

builder.Services.AddOptions<MyOptions>().BindConfiguration("MyConfig");

builder.Services.AddHostedService<MyWorker>();

var app = builder.Build();

app.MapGet("/", () => "Hello World");

app.Run();

Non-Web

var builder = Host.CreateApplicationBuilder();

builder.Logging.AddConsole();

builder.Services.AddOptions<MyOptions>().BindConfiguration("MyConfig");

builder.Services.AddHostedService<MyWorker>();

var host = builder.Build();

host.Run();
KrisG
  • 533
  • 4
  • 13