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

Dynamic Hub Configuration

Update Hub behavior dynamically at runtime based on external configuration provider changes.

In this lesson, you will learn how to modify your SignalR Hub’s behavior at runtime by reacting to external configuration changes without restarting your application.

The Challenge of Static Configuration

Typically, SignalR settings—such as message size limits, enabled transport types, or feature toggles—are baked into the Startup.cs or Program.cs files during service registration. In high-traffic microservices, however, you may need to flip a "maintenance mode" switch or adjust throttling thresholds across a cluster instantly. Hard-coding these values forces a deployment, which is inefficient.

Leveraging IOptionsMonitor<T>

To achieve dynamic configuration, we leverage the IOptionsMonitor<T> interface. Unlike IOptions<T>, which is read once at startup, IOptionsMonitor provides a fresh view of your configuration settings (e.g., from an appsettings.json, environment variables, or a centralized Configuration Provider like Azure App Configuration) whenever they change.

By injecting this into your Hub, you can adapt your logic in real-time.

Implementation Example

Consider a Hub that needs to toggle its broadcasting capability based on an external flag:

public class NotificationHub : Hub
{
    private readonly IOptionsMonitor<HubSettings> _settings;

    public NotificationHub(IOptionsMonitor<HubSettings> settings)
    {
        _settings = settings;
    }

    public async Task SendUpdate(string message)
    {
        // Accessing the current value dynamically
        if (!_settings.CurrentValue.IsBroadcastEnabled)
        {
            throw new HubException("Broadcasting is currently disabled by admin.");
        }

        await Clients.All.SendAsync("ReceiveUpdate", message);
    }
}

How It Works

When you update your configuration source, the IOptionsMonitor detects the change and updates CurrentValue immediately. The Hub does not need to be re-instantiated or the connection dropped; the next time a client invokes SendUpdate, the method logic uses the updated configuration. This allows you to toggle feature flags, change serialization settings, or update security constraints on the fly.

This pattern turns your static infrastructure into a flexible, reactive system capable of responding to operational requirements without downtime.

Key Takeaway: Use IOptionsMonitor<T> within your Hub classes to subscribe to real-time configuration updates, allowing you to modify runtime behavior dynamically without requiring a server restart.