Course contentsShow
← C#
Lesson 1442 of 1,90813. Real-time Communication with SignalRFree lesson

Hub Context Injection Patterns

Use IHubContext to push messages from outside the Hub class to specific client connections.

In this lesson, you will learn how to break out of the Hub class boundaries to push real-time updates to your users from background services or external controllers using IHubContext.

Decoupling Logic from the Hub

While the Hub class is excellent for handling incoming client requests, your application logic often resides in services, background workers, or API controllers. You cannot instantiate a Hub directly to send a message; instead, SignalR provides the IHubContext<THub> abstraction. This allows any class registered in your Dependency Injection (DI) container to broadcast messages to clients without requiring a direct client-to-server request trigger.

Injecting and Using the Context

To send a message from outside the Hub, inject IHubContext<T> into your service's constructor. This interface acts as a gateway to the connection groups and specific clients managed by the SignalR runtime.

public class OrderProcessingService
{
    private readonly IHubContext<OrderHub> _hubContext;

    public OrderProcessingService(IHubContext<OrderHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task NotifyOrderStatus(string userId, string status)
    {
        // Target a specific user connection group
        await _hubContext.Clients.User(userId)
            .SendAsync("ReceiveStatusUpdate", status);
    }
}

Strategic Scoping

When injecting IHubContext, remember that you are working with the global scope of the Hub, not a specific client instance. Because you aren't inside a Hub method, you do not have access to the Context.ConnectionId of the person who initiated a request. Therefore, you must rely on Groups, Users, or All clients to target your messages.

This pattern is highly effective for "Server-Push" scenarios, such as notifying a user that a long-running background task (like a report generation or payment processing) has completed. By decoupling the notification logic from the Hub class, you keep your Hubs thin and your business logic testable and modular.

Key Takeaway: Use IHubContext to decouple server-side event triggers from your SignalR Hubs, enabling services and controllers to push real-time updates to clients independently of user-initiated requests.