C
C#5mo ago
Ploot

Don't start hosted services on start

I'm using Microsoft.Extensions.Hosting for a project and during startup i register multiple IHostedService services, however all my other services are dependent on a singular service completing a task first, as such I'm looking for a way to have only one specific service start with the framework and have that service wake the others once it's finished
10 Replies
Mayor McCheese
Mayor McCheese5mo ago
You might be able to finagle something with a named semaphore, but there's nothing really out of the box to do this that I'm aware of.
HtmlCompiler
HtmlCompiler5mo ago
no i would use a task rather than a semaphore but still, why do you have that need it seems kinda the wrong structure maybe it's not but ⚠️
Mayor McCheese
Mayor McCheese5mo ago
It does sound like an architectural problem Any solution is really fraught with peril and likely to cause some troublesome hard to detect problems.
Ploot
PlootOP5mo ago
Reflecting, it may very well be an architectural problem. Currently I don't know of a better way of handling this. This problem arises because I am using this for a discord bot. The bot client itself is registered as a singleton with the DI collection and a hosted startup service performs configuration for this client and logs it in. My other hosted services are then using this discord client to perform various tasks independently (Think timers, checking channels for new messages, ect). My issue is coming from the other services attempting to use the client before it has chance to log in. I could just check the state of the client in each service and wait for it to be logged in before proceeding but that itself feels like a hack than a proper solution. Any ideas on a better way to go about this?
becquerel
becquerel5mo ago
why not initialise your config/perform the login before starting the app host? after you build the app you can resolve the bot client singleton before you call app.RunAsync(), which is what kicks off the hosted services
Mayor McCheese
Mayor McCheese5mo ago
That's the soundest idea
HtmlCompiler
HtmlCompiler5mo ago
to me using multiple IHostedService is wrong for this -- they are independent you would have one IHostedService that does all the initialization so you can put it there in the order you want
Mayor McCheese
Mayor McCheese5mo ago
I expect that is probably not on the table tbh
SleepWellPupper
SleepWellPupper5mo ago
You could create a custom abstraction for your secondary hosted services and execute them from your initializer hosted service after login etc. have been completed.
Want results from more Discord servers?
Add your server