Dependency Injection in API
Bloqs fully supports Dependency Injection (DI), allowing you to plug in your own services and use them inside API command or query handlers. This makes it easy to integrate custom logic, external APIs, or domain services into your Bloqs application.
Registering Services
You can register services in the API startup using the standard ASP.NET Core DI container:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
var result = await builder.BuildBloqsApi(
"sample-db",
SampleAppDeclaration.GetTypes(),
AppConstants.App.Name
);
// Register your custom service
builder.Services.AddSingleton<MyCustomService>();In this example, MyCustomService is registered as a singleton and can be injected wherever needed.
Defining a Custom Service
Here’s a simple custom service you could use to add extra logic to your application:
namespace Templates.SampleApp.Services;
public class MyCustomService
{
public string GetWelcomeMessage(string userName)
=> $"Hello {userName}, welcome to Bloqs!";
}Using Services in Handlers
Once registered, your service can be injected into command or query handlers simply by adding it to the constructor:
using Bloqs.App.Engine.Commands;
using Bloqs.App.Engine.Commands.Data;
using Templates.SampleApp.Models.Data;
namespace Templates.SampleApp.Api.Commands.Activities;
[EntityCommandHandler<Activity>]
public class NewActivity(MyCustomService myCustomService)
: ICommandHandler<NewEntityCommand, NewEntityCommandResult>
{
public Task<NewEntityCommandResult> HandleAsync(
NewEntityCommand command,
CancellationToken cancellationToken = default
)
{
var newActivity = new Activity
{
Name = "New Activity",
Description = myCustomService.GetWelcomeMessage("Developer"),
};
return Task.FromResult(NewEntityCommandResult.CreateSuccess(newActivity));
}
}
Key Points
Services are registered on the ASP.NET Core DI container (
builder.Services).You can inject services into handlers, controllers, or other services by simply declaring them in the constructor.
Use DI for business logic, external integrations, validation, logging, or any reusable functionality in your app.
Last updated