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 Bloqs.App.Engine.Commands;
using Bloqs.App.Engine.Commands.Data;
using Templates.SampleApp.Models.Data;
namespace Templates.SampleApp.UserInterface.Commands;
[EntityCommandHandler<Category>]
public class NewCategory(MyCustomService myCustomService)
: ICommandHandler<NewEntityCommand, NewEntityCommandResult>
{
public Task<NewEntityCommandResult> HandleAsync(
NewEntityCommand command,
CancellationToken cancellationToken = default
)
{
var newCategory = new Category() { Name = "New Category", Activities = [] };
// Here you could use myCustomService for validation, logging, or enrichment
return Task.FromResult(NewEntityCommandResult.CreateSuccess(newCategory));
}
}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:
@page "/welcome"
@inject MyCustomService CustomService
<h3>Welcome Page</h3>
<p>@welcomeMessage</p>
@code {
private string welcomeMessage = string.Empty;
protected override void OnInitialized()
{
welcomeMessage = CustomService.GetWelcomeMessage("Developer");
}
}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