SharpRuneOpen playground

Services and dependency injection

Register services in Program.cs, inject them into components through interfaces, and see how singleton, scoped and transient lifetimes behave in Blazor WebAssembly.

  • 25 min
  • Read, predict, then run
Blazor WebAssembly project

In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.

At a glance

Which instance each page receives

VisitSingletonScopedTransient
Home#1#1#1 and #2
Second#1#1#3
Home again#1#1#4 and #5
A second scope (model only)#1#2—

Blazor WebAssembly has one scope for the whole app, so scoped acts like singleton, while each @inject of a transient gets a new object. Pages ask for IGreeting; Program.cs picks the class.

Where services come from

builder.Services in Program.cs is an IServiceCollection, a list of registrations. Each registration says which type you will ask for, which class or factory produces it, and how long the result lives. builder.Build() turns the list into a service provider, so registrations must happen before Build. When the app starts, WebAssemblyHost creates one scope from that provider and uses it for the renderer and every component for the rest of the session.

A component asks for a service in one of three ways. @inject IGreeting Greeting in a .razor file generates a property with the [Inject] attribute. You can write that property yourself in C#, for example [Inject] private IGreeting Greeting { get; set; } = default!. Since .NET 9 a component can also receive services through its constructor, for example in a partial class with a primary constructor. For property injection, Blazor creates the component and then sets every [Inject] property before the first SetParametersAsync call, so the services are ready in OnInitialized but not in a constructor you write. If a type is not registered, Blazor throws an InvalidOperationException that names the property and the missing type.

Depend on an interface

AddSingleton<IGreeting, FriendlyGreeting>() means: when something asks for IGreeting, give it a FriendlyGreeting. The page only knows the interface. Its code calls Greet and never names the class. Changing the registration to FormalGreeting changes every component that asks for IGreeting without editing any of them. If you register the same service type twice, an injection receives the last registration.

This separation is the real value of services, more than saving a few new expressions. A test can register a fake implementation. A WebAssembly app and a server app can share pages while registering different data services, one that calls a web API with HttpClient and one that reads a database directly. Keep the interface small and describe what the page needs, not how the service does it.

Lifetimes in Blazor WebAssembly

A singleton is created the first time it is requested and then shared until the app ends. A transient is created every time it is requested: two @inject lines for the same transient type in one component give two objects, and every new component gets new ones. A scoped service is created once per scope. In ASP.NET Core on a server a scope usually lasts one HTTP request, and in server-side Blazor one circuit. Blazor WebAssembly has no request scopes, so its single app scope makes scoped services behave like singletons for the life of the browser tab.

That difference matters when code moves between hosting models. A service registered as scoped to hold per-user state is shared by the whole tab in WebAssembly, which is correct, because one tab is one user. The template registers HttpClient as scoped for the same reason. If a service should live exactly as long as one component, derive the component from OwningComponentBase, which creates its own scope and disposes it with the component. Avoid registering classes that implement IDisposable as transient: the container keeps a reference to each disposable instance it creates and disposes it only when its scope ends, which in WebAssembly means when the app ends.

Services the framework provides

WebAssemblyHostBuilder.CreateDefault registers the services Blazor itself needs. NavigationManager and IJSRuntime are singletons in WebAssembly, and configuration and logging are available as well. HttpClient is not registered for you. The project template adds it in Program.cs with BaseAddress set to builder.HostEnvironment.BaseAddress, the address the app was loaded from, and relative requests such as GetStringAsync("index.html") are resolved against it. In the browser, HttpClient sends requests through the browser's fetch API, so the browser's rules apply, including CORS for requests to other origins.

Trace ServicesLab

Program.cs registers HttpClient, IGreeting and the three lifetime classes. Each lifetime class derives from Tracked, which numbers instances per class in a static dictionary. Open the app: the Router creates Home, Blazor fills its six injected properties, and the container creates the first SingletonTag, the first ScopedTag and two TransientTag objects. The table shows Singleton #1, Scoped #1 and two different transient numbers. Add a click to each changes the Clicks property of all four objects.

Open the second page. Home is disposed and a new Second component is created. The container returns the same SingletonTag and ScopedTag objects, so their numbers and clicks are unchanged, and it creates a new TransientTag with zero clicks. OnInitializedAsync reads index.html through HttpClient and shows its title. When you go back, Home is a new component again and receives two new transients, while the singleton and scoped rows still show #1.

Common mistakes

Calling new FriendlyGreeting() inside a component works, but the page is then tied to that class, and any dependencies of the class must be created by hand too. A missing registration produces an exception the first time a page that injects the service opens, not when the app starts, so open every page after changing Program.cs. Using an injected property in a constructor fails, because property injection happens after construction; use OnInitialized instead.

Keeping per-user data in a singleton is safe in WebAssembly, where the app has one user, but the same code on a server would share the data between all users. Choose the lifetime for the meaning of the data, not for the current host. Also remember that state in a shared service does not re-render other components when it changes. A component re-renders after its own event handlers. If several visible components show the same service data, the service needs an event that they subscribe to, and each subscription must be removed in Dispose, as the next lesson shows.

Practice and review

Add an IClock interface with a Now property, a SystemClock implementation and a FixedClock that always returns the same time. Register one of them and show the time on Home, then switch the registration and confirm that no page changes. Change ScopedTag to AddTransient and predict the table before you run. Finally, replace @inject NavigationManager Navigation on Home with an [Inject] property in the @code block and confirm that the page behaves the same.

Key points
  • Register services on builder.Services before Build, and inject them with @inject, [Inject] or, since .NET 9, a constructor.
  • Depend on interfaces so that Program.cs decides the implementation.
  • Singleton: one for the app. Transient: a new one for every request. Scoped: one per scope, which in Blazor WebAssembly means one for the app.
  • NavigationManager and IJSRuntime come from the framework. HttpClient is registered by the app with the app's base address.
  • Avoid disposable transients, and use OwningComponentBase when a service should live and end with one component.
Runs on this device: SharpRune compiles the Razor components and C# here and runs the app in Preview on .NET 9 WebAssembly. The same files run on a computer with the .NET 9 SDK and dotnet run.

Services and dependency injection — Blazor WebAssembly project

Run the project

  1. Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
  2. Tap Add a click to each two times, then Open the second page. Compare the numbers and clicks, go back, and open the second page again.
  3. In Program.cs, change FriendlyGreeting to FormalGreeting and run again. No page changes, but the greeting does.
  4. Change a .razor file and tap Run again to rebuild.
  5. On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.

Download the project ↗

Project files

ServicesLab.csprojDownload file ↗
ServicesLab.csproj
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>ServicesLab</AssemblyName>
    <RootNamespace>ServicesLab</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
  </ItemGroup>

</Project>
Program.csDownload file ↗
Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using ServicesLab;
using ServicesLab.Services;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// An HttpClient whose BaseAddress is this app's address, so it can read files from wwwroot.
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

// Pages ask for IGreeting. Change FriendlyGreeting to FormalGreeting here and no page changes.
builder.Services.AddSingleton<IGreeting, FriendlyGreeting>();

// The three lifetimes. Blazor WebAssembly has one scope for the whole app,
// so the scoped service lives as long as the singleton.
builder.Services.AddSingleton<SingletonTag>();
builder.Services.AddScoped<ScopedTag>();
builder.Services.AddTransient<TransientTag>();

// NavigationManager is registered by the framework. There is nothing to add for it.

await builder.Build().RunAsync();
App.razorDownload file ↗
App.razor
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <main>
            <h1>Not found</h1>
            <p>There is no page at this address. <a href="">Go to the first page</a>.</p>
        </main>
    </NotFound>
</Router>
_Imports.razorDownload file ↗
_Imports.razor
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using ServicesLab
@using ServicesLab.Services
Pages/Home.razorDownload file ↗
Pages/Home.razor
@page "/"
@* @inject <type> <property>: the container creates or finds the service
   and sets the property before OnInitialized runs. *@
@inject IGreeting Greeting
@inject SingletonTag Singleton
@inject ScopedTag Scoped
@inject TransientTag Transient
@inject TransientTag SecondTransient
@inject NavigationManager Navigation

<PageTitle>Services Lab</PageTitle>

<main>
    <h1>Services Lab</h1>

    <p class="greeting">@Greeting.Greet("Ada")</p>
    <p class="muted">The page asked for IGreeting and received @Greeting.GetType().Name.</p>

    <h2>Lifetimes on this page</h2>
    <table>
        <thead>
            <tr><th>Injected as</th><th>Instance</th><th>Clicks</th></tr>
        </thead>
        <tbody>
            <tr><td>Singleton</td><td>#@Singleton.Number</td><td>@Singleton.Clicks</td></tr>
            <tr><td>Scoped</td><td>#@Scoped.Number</td><td>@Scoped.Clicks</td></tr>
            <tr><td>Transient</td><td>#@Transient.Number</td><td>@Transient.Clicks</td></tr>
            <tr><td>Transient, again</td><td>#@SecondTransient.Number</td><td>@SecondTransient.Clicks</td></tr>
        </tbody>
    </table>

    <div class="row">
        <button class="primary" @onclick="AddClick">Add a click to each</button>
        <button @onclick="OpenSecond">Open the second page</button>
    </div>
    <p class="muted">The two transient rows are two different objects, even on the same page.</p>
</main>

@code {
    private void AddClick()
    {
        Singleton.Clicks++;
        Scoped.Clicks++;
        Transient.Clicks++;
        SecondTransient.Clicks++;
    }

    // NavigationManager is a service too. The framework registers it for you.
    private void OpenSecond() => Navigation.NavigateTo("second");
}
Pages/Second.razorDownload file ↗
Pages/Second.razor
@page "/second"
@inject SingletonTag Singleton
@inject ScopedTag Scoped
@inject TransientTag Transient
@inject HttpClient Http
@inject NavigationManager Navigation

<PageTitle>Second page</PageTitle>

<main>
    <h1>Second page</h1>

    <p>A new component asked the same container for the same types.</p>

    <table>
        <thead>
            <tr><th>Injected as</th><th>Instance</th><th>Clicks</th></tr>
        </thead>
        <tbody>
            <tr><td>Singleton</td><td>#@Singleton.Number</td><td>@Singleton.Clicks</td></tr>
            <tr><td>Scoped</td><td>#@Scoped.Number</td><td>@Scoped.Clicks</td></tr>
            <tr><td>Transient</td><td>#@Transient.Number</td><td>@Transient.Clicks</td></tr>
        </tbody>
    </table>
    <p class="muted">Singleton and scoped kept their numbers and clicks. The transient is new.</p>

    <h2>HttpClient</h2>
    <p>BaseAddress: <code>@Http.BaseAddress</code></p>
    @if (title is null)
    {
        <p class="muted">Reading index.html…</p>
    }
    else
    {
        <p>GetStringAsync("index.html") returned @length characters. Its title is <strong>@title</strong>.</p>
    }

    <h2>NavigationManager</h2>
    <p>Current address: <code>@Navigation.Uri</code></p>
    <button @onclick='() => Navigation.NavigateTo("")'>Back to the first page</button>
</main>

@code {
    private string? title;
    private int length;

    protected override async Task OnInitializedAsync()
    {
        // A relative address is resolved against BaseAddress.
        var html = await Http.GetStringAsync("index.html");
        length = html.Length;
        var start = html.IndexOf("<title>", StringComparison.Ordinal) + "<title>".Length;
        var end = html.IndexOf("</title>", StringComparison.Ordinal);
        title = end > start ? html[start..end] : "(none)";
    }
}
Services/AppServices.csDownload file ↗
Services/AppServices.cs
namespace ServicesLab.Services;

// Components depend on this interface, not on a class.
public interface IGreeting
{
    string Greet(string name);
}

public sealed class FriendlyGreeting : IGreeting
{
    public string Greet(string name) => $"Hi {name}, nice to see you!";
}

public sealed class FormalGreeting : IGreeting
{
    public string Greet(string name) => $"Good day, {name}.";
}

// Each new instance takes the next number for its own class, so a page can show which object it received.
public abstract class Tracked
{
    private static readonly Dictionary<Type, int> created = [];

    protected Tracked()
    {
        Number = created.GetValueOrDefault(GetType()) + 1;
        created[GetType()] = Number;
    }

    public int Number { get; }

    public int Clicks { get; set; }
}

public sealed class SingletonTag : Tracked
{
}

public sealed class ScopedTag : Tracked
{
}

public sealed class TransientTag : Tracked
{
}
wwwroot/css/app.cssDownload file ↗
wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
}

body {
    margin: 0;
    font-family: -apple-system, system-ui, sans-serif;
    line-height: 1.5;
}

a, button, input, label {
    touch-action: manipulation;
}

a {
    color: var(--accent);
}

h1 {
    font-size: 1.7rem;
    margin: 0 0 12px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.15rem;
    margin: 24px 0 8px;
}

code {
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

.loading {
    padding: 32px 16px;
    color: #777;
}

.row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    margin: 12px 0;
}

input:not([type=checkbox]) {
    font: inherit;
    padding: 8px 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-width: 0;
    background: transparent;
    color: inherit;
}

button {
    font: inherit;
    padding: 8px 14px;
    border-radius: 8px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
}

button.primary {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

button:disabled {
    opacity: 0.45;
}

.muted {
    color: #777;
}

#blazor-error-ui {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #ffe8a3;
    color: #222;
}

main {
    padding: 20px 16px 40px;
    max-width: 720px;
    margin: 0 auto;
}

.greeting {
    font-size: 1.2rem;
    padding: 12px 14px;
    border-radius: 12px;
    background: rgba(107, 78, 255, 0.12);
    margin-bottom: 4px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    text-align: left;
    padding: 8px 6px;
    border-bottom: 1px solid var(--line);
}
wwwroot/index.htmlDownload file ↗
wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Services Lab</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="ServicesLab.styles.css" />
</head>
<body>
    <div id="app">
        <p class="loading">Starting .NET…</p>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">✕</span>
    </div>

    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

Expected result

Home shows Hi Ada, nice to see you! and names FriendlyGreeting. The table shows Singleton #1, Scoped #1 and two transient rows with two different numbers; Add a click to each raises every Clicks value by one. The second page shows Singleton #1 and Scoped #1 with the same clicks as before, and a transient with a new number and 0 clicks. Its HttpClient section shows the BaseAddress and the title Services Lab read from index.html, and the current address ends in /second. Every return to Home shows two new, higher transient numbers. After switching to FormalGreeting, Home shows Good day, Ada.

The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;

// The same registrations as ServicesLab's Program.cs, in a hand-written container.
var services = new Container();
services.Add<IGreeting, FriendlyGreeting>(Lifetime.Singleton);
services.Add<SingletonTag, SingletonTag>(Lifetime.Singleton);
services.Add<ScopedTag, ScopedTag>(Lifetime.Scoped);
services.Add<TransientTag, TransientTag>(Lifetime.Transient);

// Blazor WebAssembly creates one scope when the app starts and uses it for every component.
var app = services.CreateScope();

var greeting = app.Get<IGreeting>();
Console.WriteLine($"IGreeting -> {greeting.GetType().Name}: {greeting.Greet("Ada")}");

// Each page visit creates a new component, and the component asks for its services again.
string[] visits = ["Home", "Second", "Home"];
foreach (var page in visits)
{
    var transients = page == "Home"
        ? $"#{app.Get<TransientTag>().Number} and #{app.Get<TransientTag>().Number}"
        : $"#{app.Get<TransientTag>().Number}";
    Console.WriteLine($"{page,-6}  singleton #{app.Get<SingletonTag>().Number}  scoped #{app.Get<ScopedTag>().Number}  transient {transients}");
}

// A second scope, like a second user's circuit in server-side Blazor. Not something WebAssembly does.
var other = services.CreateScope();
Console.WriteLine($"Other scope  singleton #{other.Get<SingletonTag>().Number}  scoped #{other.Get<ScopedTag>().Number}");

// Swapping the implementation is one line. Code that asks for IGreeting does not change.
services.Add<IGreeting, FormalGreeting>(Lifetime.Singleton);
Console.WriteLine($"After the swap -> {services.CreateScope().Get<IGreeting>().Greet("Ada")}");

enum Lifetime { Singleton, Scoped, Transient }

sealed class Container
{
    private readonly Dictionary<Type, (Type Implementation, Lifetime Lifetime)> registrations = [];
    private readonly Dictionary<Type, object> singletons = [];

    public void Add<TService, TImplementation>(Lifetime lifetime) where TImplementation : TService, new()
    {
        registrations[typeof(TService)] = (typeof(TImplementation), lifetime);
        singletons.Remove(typeof(TService));
    }

    public Scope CreateScope() => new(this);

    internal object Get(Type service, Dictionary<Type, object> scoped)
    {
        var (implementation, lifetime) = registrations[service];
        switch (lifetime)
        {
            case Lifetime.Singleton:
                if (!singletons.TryGetValue(service, out var single)) singletons[service] = single = Activator.CreateInstance(implementation)!;
                return single;
            case Lifetime.Scoped:
                if (!scoped.TryGetValue(service, out var inScope)) scoped[service] = inScope = Activator.CreateInstance(implementation)!;
                return inScope;
            default:
                return Activator.CreateInstance(implementation)!;
        }
    }
}

sealed class Scope(Container container)
{
    private readonly Dictionary<Type, object> scoped = [];

    public T Get<T>() => (T)container.Get(typeof(T), scoped);
}

interface IGreeting
{
    string Greet(string name);
}

sealed class FriendlyGreeting : IGreeting
{
    public string Greet(string name) => $"Hi {name}, nice to see you!";
}

sealed class FormalGreeting : IGreeting
{
    public string Greet(string name) => $"Good day, {name}.";
}

// Each new instance takes the next number for its own class.
abstract class Tracked
{
    private static readonly Dictionary<Type, int> created = [];

    protected Tracked()
    {
        Number = created.GetValueOrDefault(GetType()) + 1;
        created[GetType()] = Number;
    }

    public int Number { get; }
}

sealed class SingletonTag : Tracked;
sealed class ScopedTag : Tracked;
sealed class TransientTag : Tracked;
Open C# practice

C# practice output

IGreeting -> FriendlyGreeting: Hi Ada, nice to see you!
Home    singleton #1  scoped #1  transient #1 and #2
Second  singleton #1  scoped #1  transient #3
Home    singleton #1  scoped #1  transient #4 and #5
Other scope  singleton #1  scoped #2
After the swap -> Good day, Ada.
Try this
If an instance number changes between pages, the service is transient. Do not register types that implement IDisposable as transient: the container keeps them until the app ends.

Further reading