What is Microsoft.Extensions.Hosting used for? [Answered]
I haven't used this package a lot but I'm just wondering what its purpose is in general. Is it closely related to ASP.NET? I know the
worker
project template uses the package, and the code it generates looks very ASP.NET-y with service configuration and whatnot. So like, what is it used for?12 Replies
its the home of the "generic host"
its probably your go-to for any long running process type program, like a server, discord bot or similar
it looks and feels a lot like asp.net because iirc its essentially the asp.net host stuff but extracted and made generic so it can be used for anything
works the same as asp.net, where you register things with
services.AddHostedService<YourHostedService>()
and they will then be started when the host "runs"Hmm, alright
I have heard the term "generic host" before
its just a really neat way to get all the things you most likely want in a server-type application: config files, DI, multiple background workers, lifetime management etc
gets full support for sigterm and gracious shutdown etc
What's a background worker exactly? Just a thing which does long-running work in the background?
Although I can certainly see how ASP.NET apps are essentially an adaptation of this.
well as an example, I made a discord bot that also needed to poll an api for changes
and post messages when certain data was found on that service
so I made two hostedservices, one for the bot and one for the polling service
and emitted messages using mediatr, that the bot picked up on and sent to the correct channels
Hmm, right. If I were to for instance have a Windows background service app which listens to changes in the file system, should the file system listening logic be its own hosted service?
could be, and imho probably should be yeah
So a hosted service is something which is meant to run for a (very) long time, for instance ASP.NET server applications, background services, and/or code listening to APIs?
pretty much
you dont call stop on them yourself, thats done via sigterm/sigkill 🙂
Right
So they're continuous operations
yup
✅ This post has been marked as answered!