Reputation: 1841
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 ?
Upvotes: 51
Views: 58267
Reputation: 7660
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.
Upvotes: 47
Reputation: 546
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.
Upvotes: 7