Question

.Net 6 Console app: WebApplication.CreateBuilder vs Host.CreateDefaultBuilder

I'm looking into .NET 6, and wanted to build a simple console application, with some dependency injection.

From what i can read, a lot has been done to make the startup (now just program) file, more readable. What does confuse me a bit is, that all improvements seems to have been made to WebApplication.CreateBuilderpart used in API projects, and not the Host.CreateDefaultBuilder. As mentioned in this blog

Microsofts own docs, also only seems to mention WebApplication.

To me it seems like WebApplication is only for web projects, like an API, and i can't find anything that confirms og debunks that.

Is it okay to use WebApplication in a console application, or should i rely on Host, and keep the stacked lambda expressions ?

 48  50439  48
1 Jan 1970

Solution

 45

WebApplication.CreateBuilder() is only used for web/api applications like the name implies Host.CreateDefaultBuilder() is used to build a generic host (without web services, middleware etc) which you can use to build anything other than webhost.

See for example .NET Generic Host which has not changed.

Its true that it feels a bit awkward to build console apps and/or backgroundservices at the moment.

2021-12-14

Solution

 6

This is a great reference that I use for using DI in a console application: Tutorial: Use dependency injection in .NET

Even though we're talking about console applications, DI gives you so many great options to manage hosting the app, and like any .NET application, when your application gets complex with many classes needing to share the same classes and configurations, even those sent in as CLI arguments, then DI really pays off.

2022-09-30