Skip to content

Service Providers ​

Introduction ​

Service providers are the central place where a DotBlaze application is configured, just as in Laravel. In a provider you register services in the dependency injection container, add event listeners, define route middleware aliases, and map routes.

A new application has two providers in app/Providers:

  • AppServiceProvider, for your own registrations.
  • RouteServiceProvider, which maps the routes in routes/web.cs.

NOTE

The base class is named Provider, not ServiceProvider. A web project's implicit usings import Microsoft.Extensions.DependencyInjection, which already contains a class called ServiceProvider, so the Laravel name would be ambiguous in every application. Your own classes can still be named AppServiceProvider and so on.

Writing Service Providers ​

A provider extends DotBlaze.Provider and overrides one or both of its methods:

csharp
namespace Blog.Providers;

public class AppServiceProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config)
    {
        // Register application services here.
    }

    public override void Boot(WebApplication app)
    {
        // Runs after all services are registered (event listeners, route middleware aliases, ...).
    }
}

Both methods are optional; the base class implementations do nothing.

NOTE

Generate a provider with dotblaze make:provider BillingServiceProvider. See Console Commands.

The Register Method ​

Register receives the application's IServiceCollection and the configuration. Use it only to add services to the container, the way you would in a plain ASP.NET Core Program.cs. The container has not been built yet, so do not resolve services or call facades here.

csharp
using Blog.Services;

public class AppServiceProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config)
    {
        services.AddSingleton<IPaymentGateway>(new StripeGateway(config["services:stripe:key"] ?? ""));
        services.AddScoped<InvoiceService>();
    }
}

The config parameter is the same configuration the Config facade reads, with : as the separator.

Package providers with customizable configuration must register embedded templates through Publishes(services, resources, "config", "package-config") here, while keeping default configuration available without publishing. vendor:publish handles copying; never create or overwrite application files in Register or Boot. This convention applies to new providers and packages; see Publishing Resources for the complete contract.

Because Register gets the real IServiceCollection, anything ASP.NET Core offers can be configured here, for example Data Protection key storage, extra logging providers, or a hosted service:

csharp
services.AddHostedService<NightlyReportService>();

The Boot Method ​

Boot runs after all providers have registered their services and the application has been built. It receives the WebApplication, and it runs inside a service scope, so you may use facades:

csharp
public class AppServiceProvider : Provider
{
    public override void Boot(WebApplication app)
    {
        Route.AliasMiddleware<EnsureUserIsAdmin>("admin");

        Event.Listen<PostPublished>(e => Log.Info("Post {Id} published", e.PostId));
    }
}

The template's RouteServiceProvider uses Boot to map the routes:

csharp
using Blog.Routes;

namespace Blog.Providers;

public class RouteServiceProvider : Provider
{
    public override void Boot(WebApplication app)
    {
        Web.Map();
        Api.Map();
        ConsoleRoutes.Map();
        Channels.Map();
    }
}

app.Services gives you the root service provider, and app.Environment the hosting environment. Middleware added with app.Use(...) runs after DotBlaze's own middleware, just before the controller; see Request Lifecycle.

WARNING

Boot runs in a temporary service scope that is disposed after provider booting. Do not retain services resolved from that scope. Resolve request/job services in their own scope; app.Services itself is the root provider.

Registering Providers ​

There is nothing to register. Unlike Laravel's bootstrap/providers.php, DotBlaze discovers providers automatically: every non-abstract class in the application assembly that extends Provider is created and run, wherever it lives. Providers need a public parameterless constructor.

Provider Order ​

Providers run in alphabetical order of their full type name (namespace included). All Register calls happen first, then all Boot calls in the same order. In a new application, AppServiceProvider therefore boots before RouteServiceProvider. Routes are mapped to endpoints only after every provider has booted, so a route middleware alias may be defined in any provider, before or after the routes that use it.

NOTE

Providers in installed packages are discovered too. A package provider can give its configuration defaults with MergeConfig(config, "courier", new { retries = 3 }) in Register. The application's own config/Courier.cs class and environment variables still override those defaults.

Complete Example: Inject a Service ​

One file can demonstrate discovery, registration, and constructor injection. Add this to the Blog application; it coexists with its generated providers:

csharp
// app/Providers/GreetingProvider.cs
using DotBlaze;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Blog.Providers;

public class GreetingService
{
    public string Greet(string name) => $"Hello, {name}.";
}

public class GreetingProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config) =>
        services.AddSingleton<GreetingService>();
}

public class GreetingCommand(GreetingService greeting) : Command
{
    public override string Signature => "demo:greeting {name=Ada}";
    public override Task<int> Handle()
    {
        Line(greeting.Greet(Argument("name")!));
        return Task.FromResult(0);
    }
}

Run dotblaze demo:greeting Ada. Expected: Hello, Ada. with exit code 0. No manual provider or command registration is required. A singleton is appropriate here because the service is stateless; choose a scoped lifetime for services owning request-specific state.