The SignalR documentation has a part where it explains how to use .NET's DI to inject the IHubContext into a controller/middleware, but is there any way to get a reference to/instance of a Hub from just any plain class? Does it have to specifically be a service or whatever else the DI requires in order to make this work?
To give a very contrived (and possibly wrong) example: Say we have a TestHub
and a static List<Whatever>
. Whenever a client connects to TestHub
, we create a new Whatever
and add it to the static list. Each Whatever
does one thing: asynchronously waits a random amount of time, and then somehow calls TestHub
to send a message to all clients.
Now, this might completely be an architectural issue, seeing as the static List can just as well be a Singleton service that can use DI, but the idea is that the List doesn't govern when the messages are sent, instead the Whatever
objects do that, with the random wait abstracting some nondeterministic logic.
If this scenario makes any sense, how can the Whatever
call the TestHub
?
If it doesn't, please let me know what I'm getting wrong. I'm very new to this, so I'm not really sure if the use case makes much sense in general.
Thanks in advance.
CodePudding user response:
Nope, no statics allowed. Put the class in DI and inject the IHubContext is the way to go! You can also consider using a background service.
PS: Of course, you can create your own static but that's not a route I would recommend.