More articles found at: GWS Blog
Internal engineering tools—build configuration trackers, release checklists, deployment manifests—almost always start as a shared spreadsheet or wiki page and quietly degrade into stale data, merge conflicts, and manual copy-paste errors. When your team already builds in C# and .NET, creating a real-time internal dashboard with Blazor WebAssembly and SignalR keeps your domain models, validation rules, persistence logic, and UI components inside a single strongly typed ecosystem. You eliminate the cognitive overhead and serialization drift that inevitably creep in when maintaining separate C# backends and TypeScript frontends.
In this architectural deep dive, we will build an end-to-end project artifact manager from the ground up. More importantly, we will dissect the engineering trade-offs behind every layer—comparing hosting models, RPC transports, persistence patterns, DI lifetimes, and client-side synchronization strategies—so you understand not only how to write the code, but why each decision holds up under real-world production constraints.
Architectural Blueprint
Before writing a line of code, look at how dependencies flow across the three projects we are about to structure. In clean .NET architecture, dependency direction is everything:
┌─────────────────────────┐ ┌─────────────────────────┐
│ ArtifactManager.Client │ │ ArtifactManager │
│ (Browser WASM Runtime) │ │ (ASP.NET Core Server) │
└────────────┬────────────┘ └────────────┬────────────┘
│ │
│ Both reference Shared; │
│ NEITHER references the other │
▼ ▼
┌───────────────────────────────────────┐
│ ArtifactManager.Shared │
│ (Contracts, Validation, Constants) │
└───────────────────────────────────────┘
If ArtifactManager.Client ever takes a direct project reference to the server project (ArtifactManager), the .NET linker will attempt to compile server-only assemblies (Entity Framework Core, SQL Server drivers, Microsoft.AspNetCore.App) into your WebAssembly payload—either failing compilation outright or leaking server internals into the browser's network tab.
Prerequisites
- Visual Studio 2022 (v17.8+) or Visual Studio Code with the C# Dev Kit
- .NET 8.0 SDK (Long-Term Support) or newer
- Working familiarity with C#, ASP.NET Core dependency injection, and Razor component syntax
Step 1: Scaffold a .NET 8+ Blazor WebAssembly Solution
In .NET 8+, Microsoft unified the Blazor project templates into dotnet new blazor. When configured with WebAssembly interactivity (--interactivity WebAssembly), the CLI automatically scaffolds a two-project solution:
-
ArtifactManager(Server Host): An ASP.NET Core host that renders the root HTML shell, serves the WebAssembly runtime and.dllassets, manages database connections, and hosts SignalR hubs. -
ArtifactManager.Client(WASM Client): The browser-executed WebAssembly UI project.
We will also add a third class library—ArtifactManager.Shared—so domain models, Data Annotations, and SignalR route constants live in a clean, neutral assembly referenced by both tiers.
Deep Dive: Comparing Blazor Hosting Models
Choosing an interactivity and hosting model dictates where your compute runs, how memory scales, and what happens when a developer's laptop goes into a tunnel or switches VPNs:
| Dimension | Blazor WebAssembly (Chosen) | Blazor Server | .NET 8+ Interactive Auto |
|---|---|---|---|
| Execution Runtime | Mono/WASM runtime inside the browser's JS sandbox; backend APIs/Hubs run on Kestrel. | Server-side CLR; browser is a thin DOM-patching client. | Starts on Server CLR while downloading WASM in the background, then flips to WASM on subsequent loads. |
| Server Memory Scaling | Stateless per UI: Server only allocates memory for active HTTP/SignalR requests. | Stateful per circuit: Server holds the entire component render tree and state in RAM for every open browser tab. | Hybrid: stateful during initial Server phase, stateless once transitioned to WASM. |
| Network Latency & Resilience | UI clicks, form typing, and validation happen at native local speed with zero round-trips. | Every button click or keystroke (@bind) requires a SignalR round-trip to compute the DOM diff. |
Fast once WASM caches, but initial Server phase suffers round-trip latency. |
| Architectural Complexity | Clean client/server boundary over explicit contracts (SignalR/REST). | Components can inject DbContext directly, tempting developers into tight coupling. |
Highest complexity: Every data-fetching component requires a dual-implementation abstraction (one querying EF Core directly on the server, one calling HTTP/SignalR from WASM). |
Why WebAssembly-only interactivity wins here: For an internal engineering dashboard, we want zero per-user UI memory overhead on the server, instant local UI responsiveness, and a strict physical boundary between the browser and SQL Server—without forcing the team to maintain dual data-access abstractions just to support Interactive Auto's first-load transition.
Scaffold the solution and add the Shared class library via the .NET CLI:
dotnet new blazor --interactivity WebAssembly -n ArtifactManager
cd ArtifactManager
dotnet new classlib -n ArtifactManager.Shared
dotnet sln add ArtifactManager.Shared/ArtifactManager.Shared.csproj
dotnet add ArtifactManager/ArtifactManager.csproj reference ArtifactManager.Shared/ArtifactManager.Shared.csproj
dotnet add ArtifactManager.Client/ArtifactManager.Client.csproj reference ArtifactManager.Shared/ArtifactManager.Shared.csproj
(Clean up the default Class1.cs file inside ArtifactManager.Shared after scaffolding.)
Step 2: Configure Client-Side SignalR Dependencies
In .NET 8+, the server-side SignalR runtime (Microsoft.AspNetCore.SignalR) is already compiled into the Microsoft.NET.Sdk.Web shared framework. Adding it via NuGet to the ArtifactManager server project is redundant and can introduce version-skew warnings during SDK upgrades.
Your WebAssembly client, however, targets Microsoft.NET.Sdk.BlazorWebAssembly and runs inside the browser sandbox, so it needs the SignalR client library to negotiate WebSockets over the browser's WebSocket Web API:
dotnet add ArtifactManager.Client package Microsoft.AspNetCore.SignalR.Client
Deep Dive: Choosing a Client-Server Transport
| Transport | Wire Protocol & Pattern | Serialization | Engineering Trade-offs |
|---|---|---|---|
| ASP.NET Core SignalR (Chosen) | RPC over WebSockets (full-duplex), gracefully degrading to Server-Sent Events (SSE + HTTP POST) or Long Polling behind restrictive corporate proxies. | JSON (default) or binary MessagePack over a persistent frame stream. |
Chosen: Eliminates maintaining two separate communication stacks. One logical hub connection handles both request/response RPC (InvokeAsync) and server-initiated broadcasts (Clients.All.SendAsync) when a teammate adds an artifact. |
REST (HttpClient + Controllers) |
Half-duplex request/response over HTTP/1.1 or HTTP/2. | JSON over stateless HTTP verbs. |
Rejected: REST has no native server push. Detecting changes made by other engineers requires either manual "Refresh" clicks or a background PeriodicTimer polling loop—which wastes database queries when nothing has changed and introduces polling lag. |
| gRPC-Web | Unary and server-streaming RPC over HTTP/2 (application/grpc-web). |
Protobuf binary schemas (.proto). |
Rejected: Ideal for polyglot microservice communication with strict bandwidth constraints, but forces C# developers to maintain .proto IDL files and code-generation steps instead of sharing native C# classes directly in ArtifactManager.Shared. |
Step 3: Define the Shared Domain Model
A major source of bugs in multi-tier web applications is validation drift—where the frontend enforces a 100-character limit, the backend enforces 50, and a third consumer forgets the rule entirely. By placing Artifact in ArtifactManager.Shared and annotating it with System.ComponentModel.DataAnnotations, both Blazor's <EditForm> and our SignalR hub execute the exact same metadata rules.
Create Artifact.cs inside ArtifactManager.Shared/Models/:
// ArtifactManager.Shared/Models/Artifact.cs
using System.ComponentModel.DataAnnotations;
namespace ArtifactManager.Shared.Models;
public class Artifact
{
public int Id { get; set; }
[Required(ErrorMessage = "An artifact name is required.")]
[StringLength(100, ErrorMessage = "Name cannot exceed 100 characters.")]
public string Name { get; set; } = string.Empty;
[Required(ErrorMessage = "Provide a brief description of this artifact.")]
[StringLength(500, ErrorMessage = "Description cannot exceed 500 characters.")]
public string Description { get; set; } = string.Empty;
[Required(ErrorMessage = "Specify an artifact type (e.g., Build, Release, Config).")]
[StringLength(50, ErrorMessage = "Type cannot exceed 50 characters.")]
public string Type { get; set; } = string.Empty;
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
}
Deep Dive: Data Modeling & Validation Choices
-
Data Annotations vs. FluentValidation:
System.ComponentModel.DataAnnotationslives in the .NET Base Class Library—zero third-party NuGet dependencies, native<DataAnnotationsValidator/>support in Blazor, and direct compatibility withValidator.TryValidateObjecton the server. Choose FluentValidation instead when rules become stateful or asynchronous (e.g., checking database uniqueness or conditional cross-property rules like "Release artifacts require a semantic version tag"). -
Non-nullable reference defaults (
= string.Empty): With<Nullable>enable</Nullable>active in modern .NET projects, uninitializedstringproperties generateCS8618compiler warnings and riskNullReferenceExceptionwhen bound to UI inputs. Initializing strings tostring.Emptyguarantees safe two-way binding (@bind-Value) while[Required]still rejects empty or whitespace-only submissions. -
UTC everywhere in storage (
CreatedUtc): StoringDateTime.Nowembeds the server's local clock (which shifts during Daylight Saving Time transitions or varies across cloud regions). Always persistDateTime.UtcNow(orDateTimeOffset) and convert to local time strictly inside the Razor UI (ToLocalTime()).
Step 4: Implement Persistence and the Service Layer
A classic anti-pattern in SignalR applications is injecting DbContext directly into the Hub. Hubs are transport-layer coordinators—they should handle connection context, authorization, and broadcasting, while delegating persistence to an application service. Keeping data access behind IArtifactService makes your business logic unit-testable without mocking SignalR's HubCallerContext and allows you to expose the exact same operations over a REST API or background worker later.
Install the Entity Framework Core SQL Server provider and CLI tools in the ArtifactManager server project:
dotnet add ArtifactManager package Microsoft.EntityFrameworkCore.SqlServer
dotnet add ArtifactManager package Microsoft.EntityFrameworkCore.Tools
Create the DbContext in ArtifactManager/Data/ArtifactDbContext.cs:
// ArtifactManager/Data/ArtifactDbContext.cs
using ArtifactManager.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace ArtifactManager.Data;
public class ArtifactDbContext : DbContext
{
public ArtifactDbContext(DbContextOptions<ArtifactDbContext> options)
: base(options)
{
}
public DbSet<Artifact> Artifacts => Set<Artifact>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Artifact>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
entity.Property(e => e.Description).IsRequired().HasMaxLength(500);
entity.Property(e => e.Type).IsRequired().HasMaxLength(50);
entity.HasIndex(e => e.CreatedUtc);
});
}
}
Now define the service interface and implementation in ArtifactManager/Services/:
// ArtifactManager/Services/IArtifactService.cs
using ArtifactManager.Shared.Models;
namespace ArtifactManager.Services;
public interface IArtifactService
{
Task<List<Artifact>> GetArtifactsAsync(CancellationToken cancellationToken = default);
Task<Artifact> AddArtifactAsync(Artifact artifact, CancellationToken cancellationToken = default);
Task<bool> DeleteArtifactAsync(int id, CancellationToken cancellationToken = default);
}
// ArtifactManager/Services/ArtifactService.cs
using ArtifactManager.Data;
using ArtifactManager.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace ArtifactManager.Services;
public class ArtifactService : IArtifactService
{
private readonly ArtifactDbContext _context;
public ArtifactService(ArtifactDbContext context)
{
_context = context;
}
public async Task<List<Artifact>> GetArtifactsAsync(CancellationToken cancellationToken = default)
{
return await _context.Artifacts
.AsNoTracking()
.OrderByDescending(a => a.CreatedUtc)
.ToListAsync(cancellationToken);
}
public async Task<Artifact> AddArtifactAsync(Artifact artifact, CancellationToken cancellationToken = default)
{
// Defensive reset: prevent over-posting attacks where a client sends a non-zero Id
artifact.Id = 0;
artifact.CreatedUtc = DateTime.UtcNow;
_context.Artifacts.Add(artifact);
await _context.SaveChangesAsync(cancellationToken);
return artifact;
}
public async Task<bool> DeleteArtifactAsync(int id, CancellationToken cancellationToken = default)
{
var artifact = await _context.Artifacts.FindAsync([id], cancellationToken);
if (artifact is null)
{
return false;
}
_context.Artifacts.Remove(artifact);
await _context.SaveChangesAsync(cancellationToken);
return true;
}
}
Deep Dive: Persistence Architecture Decisions
-
Focused Service vs. Generic
IRepository<T>: In Entity Framework Core,DbContextalready implements the Unit of Work pattern, andDbSet<T>already implements the Repository pattern. Adding a genericIRepository<T>wrapper on top of EF Core typically forces you into one of two traps: either exposingIQueryable<T>(which leaks EF Core query-translation quirks into upper layers anyway) or hiding EF Core's best performance features (AsNoTracking(),.Select()projections,ExecuteDeleteAsync()). A domain-specific service (IArtifactService) gives you clean, mockable boundaries while keeping full access to EF Core inside the implementation. -
Fluent API (
OnModelCreating) alongside Data Annotations: Configuring column lengths and an index onCreatedUtcinsideOnModelCreatingensures EF Core generates optimal SQL DDL (nvarchar(100)rather thannvarchar(max)) and avoids full-table scans when sorting byOrderByDescending(a => a.CreatedUtc). -
Why
AsNoTracking()matters: When EF Core executes a standard tracking query, it allocates snapshot copies of every loaded entity in itsChangeTrackerdictionary to detect mutations. For read-only dashboard lists,AsNoTracking()eliminates snapshot allocation and fixes up navigation properties faster. -
Over-posting defense (
artifact.Id = 0): BecauseArtifactis shared directly with the client, a user could theoretically craft a WebSocket frame withId = 999. ResettingId = 0and stampingCreatedUtc = DateTime.UtcNowon the server guarantees the database owns identity generation and audit timestamps.
Step 5: Build the SignalR Hub
Understanding DI lifetimes in SignalR is crucial to avoiding subtle concurrency bugs:
-
Hubinstances are Transient: ASP.NET Core creates a brand-newArtifactHubinstance for every single incoming hub method call and disposes it as soon as the method completes. You cannot store per-user state in fields on aHubclass. -
IArtifactService&ArtifactDbContextare Scoped: Because each hub invocation executes within its own DI scope, injecting a scopedIArtifactServicegives every hub call a fresh, thread-safeDbContext—with zero risk ofInvalidOperationException: A second operation was started on this context instance.
First, centralize hub route and method identifiers in ArtifactManager.Shared/HubConstants.cs so client and server never drift on string names:
// ArtifactManager.Shared/HubConstants.cs
namespace ArtifactManager.Shared;
public static class HubConstants
{
public const string HubRoute = "/artifacthub";
public const string GetArtifactsMethod = "GetArtifacts";
public const string AddArtifactMethod = "AddArtifact";
public const string ArtifactAddedEvent = "ArtifactAdded";
}
Next, implement the hub in ArtifactManager/Hubs/ArtifactHub.cs:
// ArtifactManager/Hubs/ArtifactHub.cs
using System.ComponentModel.DataAnnotations;
using ArtifactManager.Services;
using ArtifactManager.Shared;
using ArtifactManager.Shared.Models;
using Microsoft.AspNetCore.SignalR;
namespace ArtifactManager.Hubs;
public class ArtifactHub : Hub
{
private readonly IArtifactService _artifactService;
public ArtifactHub(IArtifactService artifactService)
{
_artifactService = artifactService;
}
public async Task<List<Artifact>> GetArtifacts()
{
return await _artifactService.GetArtifactsAsync(Context.ConnectionAborted);
}
public async Task AddArtifact(Artifact artifact)
{
// SignalR does not run automatic MVC model validation—validate explicitly
var validationResults = new List<ValidationResult>();
var validationContext = new ValidationContext(artifact);
if (!Validator.TryValidateObject(artifact, validationContext, validationResults, validateAllProperties: true))
{
var errors = string.Join("; ", validationResults.Select(r => r.ErrorMessage));
// HubException messages are explicitly transmitted to clients even when EnableDetailedErrors is false
throw new HubException($"Validation failed: {errors}");
}
var savedArtifact = await _artifactService.AddArtifactAsync(artifact, Context.ConnectionAborted);
// Broadcast the persisted entity (including DB-generated Id and CreatedUtc) to all clients
await Clients.All.SendAsync(HubConstants.ArtifactAddedEvent, savedArtifact, Context.ConnectionAborted);
}
}
Deep Dive: SignalR Hub Patterns
-
Why
HubExceptioninstead of rawValidationException: By default, ASP.NET Core SignalR suppresses standard exception messages (EnableDetailedErrors = false) to prevent leaking internal stack traces or SQL errors to clients—returning only a generic"An unexpected error occurred invoking 'AddArtifact' on the server."ThrowingMicrosoft.AspNetCore.SignalR.HubExceptionis SignalR's intentional mechanism for sending safe, actionable validation or business-rule error messages back to the caller. -
String Constants vs. Strongly Typed Hubs (
Hub<T>): UsingHubConstantskeeps this tutorial concise while eliminating magic strings. In larger enterprise applications, take this one step further by defining anIArtifactClientinterface inArtifactManager.Shared(Task ArtifactAdded(Artifact artifact);) and inheriting fromHub<IArtifactClient>. That convertsClients.All.SendAsync(...)into a compile-time-checked method call:await Clients.All.ArtifactAdded(savedArtifact);. -
Context.ConnectionAborted: Passing SignalR's built-inContext.ConnectionAbortedtoken into your service layer ties database query cancellation directly to the client's WebSocket health.
Step 6: Wire Up the Server Pipeline
In ArtifactManager/Program.cs, register your services and configure the .NET 8+ Blazor WebAssembly hosting pipeline.
Deep Dive: How .NET 8+ Unified Blazor Hosting Works
Unlike .NET 7's static index.html fallback model, .NET 8+ renders a server-side root Razor component (App.razor) that bootstraps the WebAssembly runtime (InteractiveWebAssemblyRenderMode). Ordering endpoints cleanly ensures SignalR WebSocket negotiations and Blazor interactive routes never collide:
-
AddRazorComponents().AddInteractiveWebAssemblyComponents()registers the server services needed to host and serve interactive WebAssembly components. -
UseStaticFiles()serves CSS, JS, and compiled_framework/*WebAssembly assets. -
UseAntiforgery()protects Razor component endpoints against Cross-Site Request Forgery. -
MapHub<ArtifactHub>(HubConstants.HubRoute)binds the SignalR WebSocket endpoint at/artifacthub. -
MapRazorComponents<App>().AddInteractiveWebAssemblyRenderMode().AddAdditionalAssemblies(...)maps the Blazor router and discovers routable pages (like/artifactsand/add-artifact) defined insideArtifactManager.Client.
// ArtifactManager/Program.cs
using ArtifactManager.Client.Pages;
using ArtifactManager.Components;
using ArtifactManager.Data;
using ArtifactManager.Hubs;
using ArtifactManager.Services;
using ArtifactManager.Shared;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.AddSignalR();
builder.Services.AddDbContext<ArtifactDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IArtifactService, ArtifactService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapHub<ArtifactHub>(HubConstants.HubRoute);
app.MapRazorComponents<App>()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(ArtifactManager.Client._Imports).Assembly);
app.Run();
Before starting the application, add a "DefaultConnection" string to ArtifactManager/appsettings.json and create your database schema:
dotnet ef migrations add InitialCreate --project ArtifactManager
dotnet ef database update --project ArtifactManager
Step 7: Build the Real-Time Artifacts Dashboard
In ArtifactManager.Client, create Pages/Artifacts.razor. Note the @rendermode InteractiveWebAssembly directive at the top of the component—in .NET 8+, interactive components inside a .Client project must declare their interactive render mode so the browser runtime activates OnInitializedAsync and @onclick handlers.
Deep Dive: Component Lifecycle, Threading, and Race-Free Stream Hydration
-
Preventing Initial-Load Race Conditions: If you subscribe to
_hubConnection.On(...)beforeGetArtifactsfinishes loading, a broadcast arriving mid-flight could either be dropped (if_artifactsis stillnull) or cause a duplicate entry onceGetArtifactsreturns. Initializing_artifactscleanly and deduplicating byartifact.Idinside the handler guarantees an exact, consistent list regardless of network timing. -
Synchronization Context (
InvokeAsync(StateHasChanged)): SignalR event handlers execute asynchronously from JS interop callbacks outside Blazor's standard UI event loop. WrappingStateHasChangedinsideawait InvokeAsync(StateHasChanged)safely marshals the render request onto Blazor's renderer dispatcher. -
Automatic Reconnect & Cleanup (
IAsyncDisposable):.WithAutomaticReconnect()handles transient network drops with progressive backoff (0s,2s,10s,30s), whileDisposeAsync()closes the underlying WebSocket when the user navigates away.
@* ArtifactManager.Client/Pages/Artifacts.razor *@
@page "/artifacts"
@rendermode InteractiveWebAssembly
@using ArtifactManager.Shared
@using ArtifactManager.Shared.Models
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager Navigation
@implements IAsyncDisposable
<PageTitle>Project Artifacts</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-3">
<h3>Project Artifacts</h3>
<div>
<button class="btn btn-outline-secondary me-2" @onclick="LoadArtifactsAsync" disabled="@(!IsConnected)">
Refresh
</button>
<a href="/add-artifact" class="btn btn-primary">New Artifact</a>
</div>
</div>
@if (!string.IsNullOrEmpty(_errorMessage))
{
<div class="alert alert-danger" role="alert">@_errorMessage</div>
}
@if (_artifacts is null)
{
<p><em>Connecting to artifact stream...</em></p>
}
else if (_artifacts.Count == 0)
{
<div class="alert alert-info">No project artifacts recorded yet.</div>
}
else
{
<table class="table table-hover align-middle">
<thead class="table-light">
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
<th>Created (Local)</th>
</tr>
</thead>
<tbody>
@foreach (var artifact in _artifacts)
{
<tr>
<td class="fw-semibold">@artifact.Name</td>
<td><span class="badge bg-secondary">@artifact.Type</span></td>
<td>@artifact.Description</td>
<td>@artifact.CreatedUtc.ToLocalTime().ToString("g")</td>
</tr>
}
</tbody>
</table>
}
@code {
private HubConnection? _hubConnection;
private List<Artifact>? _artifacts;
private string? _errorMessage;
private bool IsConnected => _hubConnection?.State == HubConnectionState.Connected;
protected override async Task OnInitializedAsync()
{
try
{
_hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri(HubConstants.HubRoute))
.WithAutomaticReconnect()
.Build();
_hubConnection.On<Artifact>(HubConstants.ArtifactAddedEvent, async artifact =>
{
_artifacts ??= [];
if (!_artifacts.Any(a => a.Id == artifact.Id))
{
_artifacts.Insert(0, artifact);
await InvokeAsync(StateHasChanged);
}
});
await _hubConnection.StartAsync();
await LoadArtifactsAsync();
}
catch (Exception ex)
{
_errorMessage = $"Unable to connect to the artifact hub: {ex.Message}";
}
}
private async Task LoadArtifactsAsync()
{
if (_hubConnection is not null && IsConnected)
{
var latest = await _hubConnection.InvokeAsync<List<Artifact>>(HubConstants.GetArtifactsMethod);
// Merge any real-time broadcasts that arrived while the initial query was in flight
if (_artifacts is not null)
{
var existingIds = latest.Select(a => a.Id).ToHashSet();
var inFlightItems = _artifacts.Where(a => !existingIds.Contains(a.Id));
latest.InsertRange(0, inFlightItems);
}
_artifacts = latest;
}
}
public async ValueTask DisposeAsync()
{
if (_hubConnection is not null)
{
await _hubConnection.DisposeAsync();
}
}
}
Design Trade-off: Page-Level HubConnection vs. Shared DI Client Service
-
Page-level
HubConnection(Used here): Keeps each Razor component self-contained with zero hidden state management—ideal when only one or two views require real-time data. -
Shared DI Client Service (Recommended for 5+ real-time views): In Blazor WebAssembly, registering a service with
builder.Services.AddScoped<ArtifactHubClient>()inArtifactManager.Client/Program.csmakes it a browser-tab singleton. CentralizingHubConnectioninside that service avoids paying a new WebSocket handshake cost on every route navigation and gives you a single place to surface global "Reconnecting..." banners across your layout.
Step 8: Create the Artifact Submission Form
Build Pages/AddArtifact.razor using Blazor's native <EditForm> component, also marked with @rendermode InteractiveWebAssembly.
Deep Dive: <EditForm> vs. Raw HTML <form>
Using <EditForm> with <DataAnnotationsValidator/> creates an internal EditContext that tracks field modification (IsModified), attaches CSS validation classes (valid, modified, invalid) automatically to <InputText> components, intercepts form submission without a full-page HTTP postback, and guarantees OnValidSubmit fires only after all Data Annotation attributes on Artifact pass. A raw <form> forces you to manually wire @onsubmit:preventDefault, track touched fields, and manage error dictionaries by hand.
@* ArtifactManager.Client/Pages/AddArtifact.razor *@
@page "/add-artifact"
@rendermode InteractiveWebAssembly
@using ArtifactManager.Shared
@using ArtifactManager.Shared.Models
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager Navigation
@implements IAsyncDisposable
<PageTitle>Add Project Artifact</PageTitle>
<h3>Add New Artifact</h3>
@if (!string.IsNullOrEmpty(_errorMessage))
{
<div class="alert alert-danger" role="alert">@_errorMessage</div>
}
<EditForm Model="@_newArtifact" OnValidSubmit="@HandleValidSubmit" class="col-md-6">
<DataAnnotationsValidator />
<ValidationSummary class="text-danger" />
<div class="mb-3">
<label for="name" class="form-label">Artifact Name</label>
<InputText id="name" class="form-control" @bind-Value="_newArtifact.Name" placeholder="e.g., Prod Release v2.4.0" />
<ValidationMessage For="@(() => _newArtifact.Name)" />
</div>
<div class="mb-3">
<label for="type" class="form-label">Type</label>
<InputText id="type" class="form-control" @bind-Value="_newArtifact.Type" placeholder="e.g., Build Config, Release, Migration" />
<ValidationMessage For="@(() => _newArtifact.Type)" />
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<InputTextArea id="description" class="form-control" rows="3" @bind-Value="_newArtifact.Description" placeholder="Summarize changes or configuration details..." />
<ValidationMessage For="@(() => _newArtifact.Description)" />
</div>
<button type="submit" class="btn btn-primary" disabled="@(!IsConnected || _isSubmitting)">
@(_isSubmitting ? "Saving..." : "Save Artifact")
</button>
<a href="/artifacts" class="btn btn-outline-secondary ms-2">Cancel</a>
</EditForm>
@code {
private HubConnection? _hubConnection;
private readonly Artifact _newArtifact = new();
private bool _isSubmitting;
private string? _errorMessage;
private bool IsConnected => _hubConnection?.State == HubConnectionState.Connected;
protected override async Task OnInitializedAsync()
{
_hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri(HubConstants.HubRoute))
.WithAutomaticReconnect()
.Build();
await _hubConnection.StartAsync();
}
private async Task HandleValidSubmit()
{
if (_hubConnection is null || !IsConnected)
{
return;
}
try
{
_isSubmitting = true;
await _hubConnection.InvokeAsync(HubConstants.AddArtifactMethod, _newArtifact);
Navigation.NavigateTo("/artifacts");
}
catch (HubException ex)
{
// Displays explicit validation or domain errors thrown via HubException on the server
_errorMessage = ex.Message;
}
catch (Exception ex)
{
_errorMessage = $"Failed to save artifact: {ex.Message}";
}
finally
{
_isSubmitting = false;
}
}
public async ValueTask DisposeAsync()
{
if (_hubConnection is not null)
{
await _hubConnection.DisposeAsync();
}
}
}
Step 9: Add Navigation Links
Finally, expose your new dashboard in the sidebar navigation (ArtifactManager/Components/Layout/NavMenu.razor) so users can reach it without typing URLs manually:
<div class="nav-item px-3">
<NavLink class="nav-link" href="artifacts">
<span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Project Artifacts
</NavLink>
</div>
Common Production Pitfalls to Avoid
-
Forgetting
@rendermode InteractiveWebAssemblyin .NET 8+: Components without an explicit interactive render mode default to static server-side rendering (SSR), meaningOnInitializedAsyncruns on the server and@onclickbutton events never fire in the browser. -
Multi-Instance Scale-Out Without a Backplane: SignalR tracks active connections in local server memory. If you deploy
ArtifactManagerbehind a load balancer with two or more container replicas, engineers connected to Instance A will never seeClients.All.SendAsyncbroadcasts triggered on Instance B unless you configure a distributed backplane—either Azure SignalR Service or Redis (Microsoft.AspNetCore.SignalR.StackExchangeRedis). -
Throwing Generic Exceptions Instead of
HubException: Standard server exceptions have their messages stripped before reaching the browser unlessEnableDetailedErrorsis enabled. UseHubExceptionfor intentional validation and domain errors. -
Unbounded Payload Sizes: By default, SignalR caps incoming hub messages at 32 KB (
MaximumReceiveMessageSize) to protect against memory-exhaustion attacks. If you later expand artifacts to carry large JSON build logs or configuration blobs, explicitly raiseMaximumReceiveMessageSizeinAddSignalR(options => ...)or upload large blobs via a streamed HTTP endpoint while sending only metadata over SignalR.
Recap
By combining a .NET 8+ Blazor WebAssembly architecture with SignalR and Entity Framework Core, you gain a responsive, real-time engineering tool without splitting your codebase across multiple languages or duplicating validation rules. Enforcing clean boundaries across Shared, Server, and Client, throwing safe HubException errors on validation failures, handling initial stream hydration without race conditions, and managing WebSocket lifecycles deterministically gives you an architecture that scales cleanly from a small internal utility to a multi-team platform.
Top comments (0)