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); appSource:https://dev.to/grantwatsondev/automating-project-artifacts-with-blazor-webassembly-and-signalr-380c