Skip to content

Latest commit

 

History

History
81 lines (59 loc) · 3.49 KB

BlazorWebAssemblyApp.md

File metadata and controls

81 lines (59 loc) · 3.49 KB

Blazor WebAssembly application

CSharp

Here's an example on GitHub Pages.

This example shows how to build a Blazor WebAssembly application with Pure.DI, exposing generated roots through the WebAssembly host container.

Note

WebAssembly uses builder.ConfigureContainer(composition) instead of UseServiceProviderFactory. Keep browser-specific services, such as HttpClient, registered in the normal Blazor service collection.

The composition setup file is Composition.cs:

using Pure.DI;
using Pure.DI.MS;
using static Pure.DI.Lifetime;

namespace BlazorWebAssemblyApp;

partial class Composition : ServiceProviderFactory<Composition>
{
    // IMPORTANT:
    // Only composition roots (regular or anonymous) can be resolved through the `IServiceProvider` interface.
    // These roots must be registered using `Root<>(...)` or `Roots<>()` calls.
    [System.Diagnostics.Conditional("DI")]
    private static void Setup() => DI.Setup()
        .Root<IAppViewModel>()
        .Root<IClockViewModel>()

        .Bind().As(Singleton).To<ClockViewModel>()
        .Bind().To<ClockModel>()
        .Bind().As(Singleton).To<Ticks>()

        // Infrastructure
        .Bind().To<MicrosoftLoggerAdapter<TT>>()
        .Bind().To<CurrentThreadDispatcher>();
}

The composition class inherits from ServiceProviderFactory<T>, where T is the composition class itself. Only registered roots can be resolved through the Microsoft IServiceProvider, so each view model consumed by the host must be listed with Root.

The web application entry point is in the Program.cs file:

var builder = WebAssemblyHostBuilder.CreateDefault(args);

// Uses Composition as an alternative IServiceProviderFactory
using var composition = new Composition();
builder.ConfigureContainer(composition);

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

await builder.Build().RunAsync();

The project file looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">
    ...
    <ItemGroup>
        <PackageReference Include="Pure.DI" Version="2.5.7">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Pure.DI.MS" Version="2.5.7" />
    </ItemGroup>

</Project>

It contains additional references to NuGet packages:

Pure.DI NuGet DI source code generator
Pure.DI.MS NuGet Add-ons for Pure.DI to work with Microsoft DI