A Blazor Server tab can stay open for days. Behind it, a SignalR circuit keeps one dependency-injection scope alive for the entire connection — so a license you validated the moment the circuit opened is still the answer the app gives on day three, long after the lease expired and the trial lapsed. In request-per-scope ASP.NET Core that bug can't happen: the scope dies with the request. In Blazor Server it is the default, and it is the single thing most teams get wrong when they bolt licensing onto a server-rendered app.
The real question — where does a license live in a circuit?
The instinct is to register a scoped LicenseService, read it in your components, and move on. In MVC that is correct. In Blazor Server it quietly breaks, because a scoped service is not request-scoped — it is circuit-scoped. Blazor creates exactly one scope when the browser establishes its circuit and keeps it until the circuit is torn down. Navigating between pages does not make a new scope. Clicking buttons does not make a new scope. The scope is the connection.
So a license read once in a scoped constructor is frozen for the whole session. A customer whose 30-day evaluation expires at midnight keeps every paid feature until they close the tab. That is not a theoretical edge case; long-lived dashboards are exactly the Blazor Server sweet spot.
The fix has three moving parts: a scoped context that holds the current entitlement snapshot and announces changes, a CircuitHandler that fills it at connect time and keeps it fresh for the circuit's life, and components that react to changes by dropping into a degraded, read-only mode instead of lying about what is licensed.
Step 1 — a scoped context that fails closed and announces change
The context holds the latest LicenseInfo and raises an event when it is replaced. It starts in a fail-closed state so that if anything goes wrong before the handler runs — prerendering, a race, a thrown handler — the app behaves as unlicensed rather than unlocked.
using Keyright;
public sealed class CircuitLicenseContext
{
private LicenseInfo _info = LicenseInfo.None; // fail closed until the handler fills it
public LicenseInfo Current => _info;
public event Action? Changed;
public bool IsEnabled(string key)
=> _info.IsValid && _info.Entitlements.IsEnabled(key);
public void Update(LicenseInfo next)
{
_info = next;
Changed?.Invoke();
}
}
IsEnabled fails closed twice over: an invalid license short-circuits, and the Keyright SDK's own IsEnabled returns false for any entitlement that isn't present. There is no path where an absent entitlement reads as enabled.
Step 2 — a CircuitHandler that keeps the snapshot fresh
CircuitHandler is Blazor Server's lifecycle hook. Register one as scoped and Blazor instantiates it per circuit, calling OnCircuitOpenedAsync when the connection comes up and OnCircuitClosedAsync when it is torn down. We snapshot the license at open, then run a PeriodicTimer for the life of the circuit so a mid-session expiry is caught instead of cached forever.
using Keyright;
using Microsoft.AspNetCore.Components.Server.Circuits;
public sealed class LicenseCircuitHandler : CircuitHandler, IDisposable
{
private readonly KeyrightClient _client;
private readonly CircuitLicenseContext _context;
private readonly CancellationTokenSource _cts = new();
public LicenseCircuitHandler(KeyrightClient client, CircuitLicenseContext context)
=> (_client, _context) = (client, context);
public override Task OnCircuitOpenedAsync(Circuit circuit, CancellationToken ct)
{
_context.Update(_client.Validate()); // snapshot at connect time
_ = RevalidateLoop(_cts.Token); // keep it fresh; don't await
return Task.CompletedTask;
}
private async Task RevalidateLoop(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
try
{
while (await timer.WaitForNextTickAsync(ct))
{
LicenseInfo next = _client.Validate(); // local, no network round-trip
LicenseInfo now = _context.Current;
if (next.Edition != now.Edition || next.IsValid != now.IsValid)
_context.Update(next); // raises Changed → UI refresh
}
}
catch (OperationCanceledException) { /* circuit closed */ }
}
public override Task OnCircuitClosedAsync(Circuit circuit, CancellationToken ct)
{
_cts.Cancel();
return Task.CompletedTask;
}
public void Dispose() => _cts.Dispose();
}
Validate() is pure local computation — it verifies the signature against the embedded public key, checks expiry, node-lock and clock state, and reads the entitlement set from the lease the SDK already cached. It never touches the network and never throws, so running it every five minutes is cheap and safe. We only raise Changed when the edition or validity actually flips, so a steady-state circuit does no re-rendering at all; the event fires exactly on the transition that matters — paid to Community Edition, valid to expired.
Step 3 — components that degrade instead of lying
A component subscribes to Changed in OnInitialized, marshals the re-render onto the renderer's synchronization context with InvokeAsync, and unsubscribes on dispose. When the edition flips, the gated control is replaced by a read-only notice rather than silently vanishing.
@implements IDisposable
@inject CircuitLicenseContext License
@if (License.IsEnabled("feature.export"))
{
<button class="btn" @onclick="Export">Export report</button>
}
else
{
<p class="notice">
Export is read-only on @License.Current.Edition.
Your license lapsed — renew to re-enable it without reloading.
</p>
}
@code {
protected override void OnInitialized() => License.Changed += OnLicenseChanged;
private void OnLicenseChanged() => InvokeAsync(StateHasChanged);
public void Dispose() => License.Changed -= OnLicenseChanged;
}
The Changed event is raised from the timer's thread pool thread; InvokeAsync(StateHasChanged) hops back onto the circuit's dispatcher so the re-render is thread-safe. The user sees the Export button turn into a renew prompt the moment the license expires, in a tab they never touched — no reload, no hard lockout, no crash.
Wiring it up
Three registrations. The client is a singleton (it loads the public key once and is immutable); the context and the handler are scoped so there is one of each per circuit.
builder.Services.AddSingleton(new KeyrightClient(o => o.PublicKey = PublicKeys.App));
builder.Services.AddScoped<CircuitLicenseContext>();
builder.Services.AddScoped<CircuitHandler, LicenseCircuitHandler>();
Registering CircuitHandler as the service type (not the concrete class) is deliberate — Blazor discovers every CircuitHandler registration and drives all of them, so this composes with any other circuit hooks you already have.
Caveats — where this bites
Prerendering has no circuit. During the initial server prerender there is no SignalR connection, so OnCircuitOpenedAsync has not run and the context is still LicenseInfo.None. That is why it fails closed: the first server-rendered paint shows the unlicensed UI, then the circuit connects and, if licensed, the features light up. If that flicker is unacceptable, disable prerendering for the gated page or read the license synchronously during prerender from the singleton client.
Every tab is a circuit. Two tabs mean two scopes, two contexts, two revalidation loops — and, if you claim a floating seat per circuit, two seats. When seats are scarce, key the seat claim on the authenticated user, reference-count their open circuits across OnCircuitOpenedAsync/OnCircuitClosedAsync, and release only when the count hits zero. See floating concurrent seats for the lease-counting side.
Five minutes is a window, not a guarantee. A license that expires at 12:00 is enforced by 12:05 at the latest, never before. Shorten the interval for tighter enforcement, but remember the real line of defense is server-side: a circuit-scoped UI gate is a courtesy to honest users, not a substitute for checking the entitlement where the privileged work actually executes. Pair it with entitlements as authorization policies on your API surface.
Takeaway
Blazor Server's scope-is-the-circuit model is the one fact that turns a correct ASP.NET Core licensing pattern into a silent bug. Hold the entitlement snapshot in a scoped context, refresh it from a CircuitHandler timer for as long as the circuit lives, and let components subscribe and degrade gracefully — and a tab left open for a week enforces its license as faithfully as one just opened. Keyright's offline, never-throwing Validate() is what makes the revalidation loop cheap enough to run forever.
Top comments (0)