[ad_1]
Not too long ago I’ve inherited an ASP.NET core utility, which can be my first time working with the framework. Working with the appliance initializing controllers felt very repetitive since all controllers used a number of frequent companies like loggers. ASP.NET core makes service entry straightforward with dependency injection, however it’s difficult to remain true to the DRY precept when each controller is initialized with the identical few companies.
Within the code above, a number of of the companies being injected are additionally being utilized in different controllers. So, it turns into very repetitive to should initialize all controllers the identical method. However transferring the injection of frequent companies to a base controller is not going to work, as seen under.
Having the frequent service injected in a base controller constructor will defeat the aim of a base controller and change into redundant. The companies nonetheless must be outlined in every little one controller.
Answer
Create Properties As a substitute
What I discovered to work greatest for my wants and the appliance is to outline all frequent companies as properties. With ASP.NET Core the Microsoft.Extensions.DependencyInjection identify house provides us entry to the next extension methodology HttpContext.RequestServices.GetService<T>.
Warning
With this strategy, one factor to remember is that it makes use of the HttpContext object, and if it isn’t accessible, you will be unable to make use of the service. And bear in mind the companies nonetheless must be registered within the Startup.cs > ConfigureServices methodology.
Base Controller
Baby Controller
Now controllers are solely required to inject the companies particular to them. Thus, sticking to the DRY precept and preserving the controller constructors clear.
Facet observe, Microsoft appears to desire injection over RequestServices:
The companies accessible inside an ASP.NET Core request are uncovered by the HttpContext.RequestServices assortment. When companies are requested from inside a request, the companies and their dependencies are resolved from the RequestServices assortment.
The framework creates a scope per request and RequestServices exposes the scoped service supplier. All scoped companies are legitimate for so long as the request is energetic.
Word: Want requesting dependencies as constructor parameters to resolving companies from the RequestServices assortment. This leads to courses which are simpler to check.
Hold Studying: C# Home windows Service Debug Hack >>
[ad_2]