Facades
- Introduction
- Complete Example: Custom Facade and Fake
- When to Use Facades
- How Facades Work
- Faking Facades in Tests
- Writing Your Own Facade
- Facade Reference
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.
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:
// 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>():
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:
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():
[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:
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:
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
| Facade | Service resolved | Fake | Documentation |
|---|---|---|---|
Auth | AuthManager (session authentication) | – | Authentication |
Config | IConfiguration | Facade.Swap<IConfiguration>, Config.Set | Configuration |
Crypt | IDataProtectionProvider | – | Encryption |
DB | DatabaseManager (EF Core) | – (use a SQLite test database) | Database |
Event | IEventDispatcher | Event.Fake() | Events |
Hash | Hasher (PBKDF2-SHA256) | – | Hashing |
Http | IHttpClientFactory | Http.Fake() | HTTP Client |
Log | ILoggerFactory | Log.Fake() | Logging |
Queue | IQueue | Queue.Fake() | Queues |
Route | RouteRegistry | – | Routing |
Storage | StorageManager | Storage.Fake() | File Storage |
Cache | CacheManager | Cache.Fake() | Cache |
Mail | IMailer | Mail.Fake() | |
Notification | INotificationDispatcher | Notification.Fake() | Notifications |
Gate | GateRegistry | – (use Gate.ForUser(user)) | Authorization |
Password | AuthManager + password_reset_tokens | – | Resetting Passwords |
RateLimiter | RateLimiterStore (backed by cache) | – (use Cache.Fake()) | Rate Limiting |
URL | UrlGenerator | – | URL Generation |
Live | LiveManager | – | Live Components |
Redis | RedisConnections (DotBlaze.Redis) | – | Redis |
Date | TimeProvider | Date.Freeze, Date.Use | Dates |
Validator | RuleSet<T> / FluentValidation | – | Validation |
Cookie | Request-scoped cookie jar | HTTP tests | Cookies |
Context | Scoped metadata repository | Fresh service scope | Context |
Pipeline | Typed handlers; class handlers use DI | Delegate handlers | Pipelines |
Artisan | Application command runner | Capture output with TextWriter | Console |
Image | Magick.NET (DotBlaze.Image) | Real in-memory images / Storage.Fake() | Images |
Vite | Asset manifest / development hot file | Temporary asset files | Vite |
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:
// 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.