Dependency Injection in the Blazor UI

Just like in the API, you can use Dependency Injection (DI) in the Blazor UI project. This allows you to reuse services, share business logic, or integrate external APIs directly in your UI command handlers or Blazor components.


Registering Services

You can register services in the Blazor WebAssembly host builder:

var builder = WebAssemblyHostBuilder.CreateDefault(args);

var apiEndpoint =
    builder.Configuration["ApiEndpoint"]
    ?? throw new InvalidOperationException("ApiEndpoint not set");

var result = await builder.BuildBloqsUserInterface(
    apiEndpoint,
    SampleAppDeclaration.GetTypes(),
    AppConstants.App.Name
);

// Register your custom service
builder.Services.AddSingleton<MyCustomService>();

Here, MyCustomService is registered as a singleton and can be injected into handlers or components.


Using Services in Command Handlers

Once registered, your service can be injected into command handlers for your Blazor UI:


Using Services in Blazor Components

You can also inject services directly into Blazor components using the @inject directive (or [Inject] attribute in code-behind).

Example:

This way, MyCustomService is available inside your Razor component and can be used for logic, API calls, or UI enrichment.


Key Points

  • Services are registered on the Blazor DI container (builder.Services).

  • You can inject services into command handlers or Blazor components.

  • Use DI in the UI to add custom logic, validation, or integrations without modifying the core Bloqs framework.

Last updated