In the following code (from https://github.com/JasonGT/NorthwindTraders/blob/master/Src/WebUI/Controllers/BaseController.cs), it's a base control inherited by all controllers.
[ApiController]
[Route("api/[controller]/[action]")]
public abstract class BaseController : ControllerBase
{
private IMediator _mediator;
protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}
The sub-class controllers then just use the property of Mediator
.
How it differs from just adding services.AddScope<Mediator>();
in Startup.cs
and then inject mediator
.
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// services.AddSingleton<Mediator>();
services.AddScope<Mediator>();
We can add the service to the service container in the ConfigureServices method of the startup class. There are three different life options available: Transient, Scoped, and Singleton.
We need to add the namespace, i.e., Microsoft. Extension. DependencyInjection. So, in the startup class, inside the ConfigureServices method, we need to add our dependency into the service collection which will dynamically inject whenever and wherever we want in the project.
How can we inject the service dependency into the controller C# Asp.net Core? ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.
IServiceCollection is the collection of the service descriptors. We can register our services in this collection with different lifestyles (Transient, scoped, singleton) IServiceProvider is the simple built-in container that is included in ASP.NET Core that supports constructor injection by default.
The difference is that you don't need to inject IMediator
to the constructor of BaseController and to all sub classes of BaseController.
So it's saves some boilerplate, but also makes the dependency less explicit.
Side note, Microsoft recommends to prefer the injection over RequestServices
The services available within an ASP.NET Core request from HttpContext are exposed through the HttpContext.RequestServices collection.
Request Services represent the services configured and requested as part of the app. When the objects specify dependencies, these are satisfied by the types found in RequestServices, not ApplicationServices.
Generally, the app shouldn't use these properties directly. Instead, request the types that classes require via class constructors and allow the framework inject the dependencies. This yields classes that are easier to test.
Note
Prefer requesting dependencies as constructor parameters to accessing the RequestServices collection.
See Microsoft docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With