Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
In this section, I’m going to cover how you can use SignalR outside of a Hub. In most asp.net core applications, you will likely want to communicate with the connect clients from within your application but outside of a Hub. You can accomplish this by using the HubContext.
For example, an ASP.NET Core MVC Controller or any other class that is instantiated by ASP.NET Core’s Dependency Injection.
This blog post is apart of a course that is a complete step-by-setup guide on how to build real-time web applications using ASP.NET Core SignalR. By the end of this course, you’ll be able to build real-world, scalable, production applications using the tools and techniques provided in this course.
If you haven’t already, check out the prior sections of this course.
HubContext
The HubContext allows you to send messages to your connected clients. It has many of the same features to communicate with clients as when you are inside of a Hub.
In order to get an instance of the HubContext, you need to be using dependency injection by specifying you want an IHubContext<T> in the constructor. Where T is your Hub.
In the example below I’m creating an ASP.NET Core MVC Controller that is taking the IHubContext<MessageHub> injected via the constructor.
Once you have the IHubContext<T> in your controller or any class that was created by the DI container, you can access almost all of the similar methods that are on a Hub.
In this example, I’ve created a HttpPost route that will accept a string and then I’m using the Clients.All.SendAsync() to send a message to all connected clients.
Get The Course!
You’ve got several options:
- Check out my Practical ASP.NET Core SignalR playlist on my CodeOpinion YouTube channel.
- Access the full course now by enrolling for free on Teachable.
- Follow along with the blog post series here on CodeOpinion.com
|
Source Code
All of the source code for this blog post and this course is available the Practical.AspNetCore.SignalR repo on GitHub.