Skip to content

Facades ​

Introduction ​

Throughout the DotBlaze documentation you will see code that calls static methods on classes such as Config, Log, Queue, or Storage. These are facades: static front doors to services registered in ASP.NET Core's dependency injection container. As in Laravel, they give you a short, memorable syntax while the real work is done by an ordinary, replaceable service.

csharp
public IActionResult Index()
{
    Log.Info("Home page viewed");

    return View(model: Config.Get<string>("app.name"));
}

Facades live in the DotBlaze namespace, which the template imports globally, so no using is needed.

Not every static class is a facade. Str, Arr, and Collection are pure helpers with no state and no container behind them, just as Str and Arr are not facades in Laravel. See Helpers and Collections.

When to Use Facades ​

Facades are convenient in controllers, jobs, listeners, seeders, and migrations, where they keep the code short. Constructor injection is always an alternative, because every facade only forwards to a service that is also available to inject.

Facades vs. Dependency Injection ​

These two controllers do the same thing:

csharp
// Facade style
public class ReportController : BaseController
{
    public IActionResult Index()
    {
        Log.Info("Report opened");
        return View();
    }
}

// Constructor injection style
public class ReportController(ILogger<ReportController> logger) : BaseController
{
    public IActionResult Index()
    {
        logger.LogInformation("Report opened");
        return View();
    }
}

Pick whichever reads better for the class at hand. Facades make dependencies less visible, so if a class starts calling many different facades, that can be a sign it is doing too much.

How Facades Work ​

A DotBlaze facade is a static class whose methods call Facade.Resolve<T>():

csharp
public static class Hash
{
    static Hasher Hasher => Facade.Resolve<Hasher>();

    public static string Make(string password) => Hasher.Make(password);
    // ...
}

Facade.Resolve<T>() returns the fake installed for T, if there is one, and otherwise resolves T from the active service scope, ServiceScope.Current. During an HTTP request the active scope is the request's own HttpContext.RequestServices, which DotBlaze sets in its middleware pipeline. Scoped services are therefore shared within one request and disposed when it ends, exactly as with constructor injection.

The scope is stored in an AsyncLocal, so it follows your code across await calls and is never shared between two concurrent requests.

Facades Outside Requests ​

DotBlaze sets up a scope for you in queue jobs, queued listeners, console commands, seeders, migrations, and provider Boot methods. In any other background code, such as your own BackgroundService or a timer, there is no active scope, and a facade call throws:

No active service scope. Facades can only be used inside an HTTP request,
or inside ServiceScope.Run(...) for jobs, commands, and background code.

Wrap the work in ServiceScope.Run, passing the root service provider. It creates a new DI scope, makes it active for the code inside, and disposes it afterwards:

csharp
public class NightlyReportService(IServiceProvider services) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await ServiceScope.Run(services, async () =>
            {
                var count = await DB.Select("select id from posts");
                Log.Info("Nightly report: {Count} posts", count.Count);
            });

            await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
        }
    }
}

Register the service in a provider with services.AddHostedService<NightlyReportService>(). ServiceScope.TryCurrent returns the active scope, or null when there is none.

Faking Facades in Tests ​

Facades that talk to the outside world have a Fake() method that swaps in a recording implementation with assertion methods, like Laravel's Queue::fake():

csharp
[Fact]
public void Logs_the_login()
{
    var log = Log.Fake();

    Log.Info("User {Id} login", 7);

    log.AssertLogged(e => e.Message == "User 7 login");
}

Fakes are stored per async flow, not in a static field, so tests running in parallel never see each other's fakes.

WARNING

Call Fake() directly in the test method, not inside an async helper method. An AsyncLocal value set inside an async method does not flow back to its caller, so the fake would disappear when the helper returns.

Underneath, Fake() uses Facade.Swap<T>(instance), which you may call yourself to replace any service a facade resolves. For example, a test can give the Config facade its own configuration:

csharp
Facade.Swap<IConfiguration>(new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string?> { ["app:name"] = "Test" })
    .Build());

Assert.Equal("Test", Config.Get<string>("app.name"));

See Mocking for each fake's assertions.

Writing Your Own Facade ​

A facade for your own service is a static class that forwards to Facade.Resolve<T>(). Register the service in a provider, then:

csharp
namespace Blog.Support;

public interface IPaymentGateway
{
    Task<string> Charge(decimal amount, string token);
}

public static class Payment
{
    public static Task<string> Charge(decimal amount, string token) =>
        Facade.Resolve<IPaymentGateway>().Charge(amount, token);

    public static FakePaymentGateway Fake()
    {
        var fake = new FakePaymentGateway();
        Facade.Swap<IPaymentGateway>(fake);
        return fake;
    }
}

NOTE

Avoid giving a namespace the same name as a facade (for example Blog.Http or Blog.Storage): inside that namespace, the name refers to the namespace and hides the facade. See Directory Structure.

Facade Reference ​

FacadeService resolvedFakeDocumentation
AuthAuthManager (session authentication)–Authentication
ConfigIConfigurationFacade.Swap<IConfiguration>, Config.SetConfiguration
CryptIDataProtectionProvider–Encryption
DBDatabaseManager (EF Core)– (use a SQLite test database)Database
EventIEventDispatcherEvent.Fake()Events
HashHasher (PBKDF2-SHA256)–Hashing
HttpIHttpClientFactoryHttp.Fake()HTTP Client
LogILoggerFactoryLog.Fake()Logging
QueueIQueueQueue.Fake()Queues
RouteRouteRegistry–Routing
StorageStorageManagerStorage.Fake()File Storage
CacheCacheManagerCache.Fake()Cache
MailIMailerMail.Fake()Mail
NotificationINotificationDispatcherNotification.Fake()Notifications
GateGateRegistry– (use Gate.ForUser(user))Authorization
PasswordAuthManager + password_reset_tokens–Resetting Passwords
RateLimiterRateLimiterStore (backed by cache)– (use Cache.Fake())Rate Limiting
URLUrlGenerator–URL Generation
LiveLiveManager–Live Components
RedisRedisConnections (DotBlaze.Redis)–Redis
DateTimeProviderDate.Freeze, Date.UseDates
ValidatorRuleSet<T> / FluentValidation–Validation
CookieRequest-scoped cookie jarHTTP testsCookies
ContextScoped metadata repositoryFresh service scopeContext
PipelineTyped handlers; class handlers use DIDelegate handlersPipelines
ArtisanApplication command runnerCapture output with TextWriterConsole
ImageMagick.NET (DotBlaze.Image)Real in-memory images / Storage.Fake()Images
ViteAsset manifest / development hot fileTemporary asset filesVite

Validator, delegate pipelines, and in-memory image processing are stateless entry points and do not require a service scope. Date also works outside a scope using the system clock.

Schema is used inside migrations only and does not resolve a service.

Complete Example: Custom Facade and Fake ​

The payment illustration requires application-specific gateway implementations. This complete Blog example instead uses an in-memory greeting and supplies every type:

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

namespace Blog.Providers;

public interface IDocumentationGreeting
{
    string Text { get; }
}

public record DocumentationGreeting(string Text) : IDocumentationGreeting;

public static class GreetingFacade
{
    public static string Text => Facade.Resolve<IDocumentationGreeting>().Text;
    public static void Fake(string text) =>
        Facade.Swap<IDocumentationGreeting>(new DocumentationGreeting(text));
}

public class FacadeDemoProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config) =>
        services.AddSingleton<IDocumentationGreeting>(new DocumentationGreeting("Hello"));
}

public class FacadeDemoCommand : Command
{
    public override string Signature => "demo:facade";
    public override Task<int> Handle()
    {
        if (GreetingFacade.Text != "Hello")
            throw new InvalidOperationException("Default service was not resolved.");
        GreetingFacade.Fake("Hello from the fake");
        if (GreetingFacade.Text != "Hello from the fake")
            throw new InvalidOperationException("Facade swap did not apply.");
        Line(GreetingFacade.Text);
        return Task.FromResult(0);
    }
}

Run dotblaze demo:facade. Expected: Hello from the fake. The container owns the real service; the override follows the current async flow. Constructor-injected references already obtained from DI are not replaced by a facade swap. See the HTTP fake example for a real framework facade with request assertions.