C
C#•3y ago
Thinker

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
Pobiega
Pobiega•3y ago
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"
Thinker
ThinkerOP•3y ago
Hmm, alright I have heard the term "generic host" before
Pobiega
Pobiega•3y ago
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
Thinker
ThinkerOP•3y ago
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.
Pobiega
Pobiega•3y ago
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
Thinker
ThinkerOP•3y ago
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?
Pobiega
Pobiega•3y ago
could be, and imho probably should be yeah
Thinker
ThinkerOP•3y ago
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?
Pobiega
Pobiega•3y ago
pretty much you dont call stop on them yourself, thats done via sigterm/sigkill 🙂
Thinker
ThinkerOP•3y ago
Right So they're continuous operations
Pobiega
Pobiega•3y ago
yup
Accord
Accord•3y ago
✅ This post has been marked as answered!

Did you find this page helpful?