How to avoid redundant DI code in ASP.NET Core

When doing the job with controllers in world wide web programs using ASP.Net Main or ASP.Net Main MVC, you could possibly have encountered code redundancy. For case in point, you could possibly have occur throughout controllers that use dependency injection (DI) to inject services that they need. If the code that injects the dependencies has been reused in many controllers, then you have code redundancy and violation of the DRY principle (never repeat oneself).

This post appears at DI code redundancy and displays how to make your customized foundation controller to stay away from such problems. To perform with the code illustrations furnished in this post, you should have Visual Studio 2019 put in in your process. If you never by now have a duplicate, you can download Visual Studio 2019 below.

Create an ASP.Net Main MVC venture in Visual Studio

Very first off, let us produce an ASP.Net Main venture in Visual Studio 2019. Subsequent these actions will produce a new ASP.Net Main MVC venture in Visual Studio 2019.

  1. Start the Visual Studio IDE.
  2. Click on on “Create new venture.”
  3. In the “Create new project” window, decide on “ASP.Net Main World-wide-web App (Design-See-Controller)” from the list of templates shown.
  4. Click on Future.
  5. In the “Configure your new project” window, specify the title and locale for the new venture.
  6. Optionally examine the “Place solution and venture in the exact same directory” examine box, depending on your tastes.
  7. Click on Future.
  8. In the “Additional Information” window demonstrated future, decide on .Net 5. as the focus on framework from the drop-down list at the major. Leave the “Authentication Type” as “None” (default).
  9. Make certain that the examine packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we will not be using any of those people attributes below.
  10. Click on Create.

A new ASP.Net Main MVC venture will be established. We’ll use this venture to perform with dependency injection in the subsequent sections of this post.

Now observe the actions outlined beneath to produce additional controllers in your venture.

  1. Correct-click on the Controllers solution folder.
  2. Pick out Include -> Controller.
  3. In the “Add New Scaffolded Item” dialog, decide on API as the template (by default MVC will be selected).
  4. Pick out the product “API Controller with read/produce steps.”
  5. Click on Include.
  6. In the “Add New Item” dialog demonstrated future, specify a title for your new controller.
  7. Click on Include.

Designed-in foundation controller lessons in ASP.Net Main

There are two foundation lessons for controllers, particularly ControllerBase and Controller. The ControllerBase class implements the IController interface and presents the implementation for several approaches and houses. It defines an abstract approach named ExecuteCore that is applied to find the motion approach and execute it. You should use ControllerBase whenever you are building your APIs.

The Controller class extends the ControllerBase class, presents the ExecuteCore approach, and provides several approaches you can use in your controller lessons such as See() and Redirect(). Like ControllerBase, the Controller class is a foundation controller class with look at assist. Hence you should use the Controller class whenever you’re making your controllers in ASP.Net Main MVC. The ControllerBase class presents the needed integration with routing and HttpContext so that you can leverage them. It also consists of the code needed for controlling ViewData and TempData.

Put into action a foundation controller class in ASP.Net Main

When we produce a new API controller class in ASP.Net Main, it extends the ControllerBase class by default. Future, we’ll produce our implementation of a foundation controller. Our foundation controller class will increase the ControllerBase class of the framework.

In this article is an entity class we will be using in this case in point:

public class Purchase
        public int Id get established
        public int CustomerId get established
        public string Handle get established        

Now produce the subsequent interface named IOrderManager that consists of the declaration of a approach named ProcessOrder.

public interface IOrderManager
        public void ProcessOrder(Purchase get)

Future produce the OrderManager class that extends the IOrderManager interface and implements its ProcessOrder approach.

public class OrderManager : IOrderManager

   public void ProcessOrder(Purchase get)
      throw new Process.NotImplementedException()

The subsequent code listing displays how you can produce a foundation controller class by deriving it from the ControllerBase class.

public class BaseController : ControllerBase

   secured readonly ILogger _logger
   secured readonly IOrderManager _orderManager
   public BaseController(ILogger logger,
   IOrderManager orderManager)
       _logger = logger
       _orderManager = orderManager

Extend your customized foundation controller in ASP.Net Main

You can now produce your controllers by deriving from this customized foundation controller we just established. The subsequent code listing illustrates how you can produce your controller class by extending it from the newly established foundation controller class.

public class OrderController : BaseController

   non-public readonly ILogger _logger
   public string Get()
       return "OrderController"
   public void ProcessOrder(Purchase get)

Having said that, you will discover that the over code will not compile. In this article is the mistake you will be introduced with in Visual Studio:

base controller class error IDG

The mistake states that you need to put into action a different argument constructor with the exact same arguments as the constructor of the BaseController class. But why? If you’re heading to replicate the dependency injection code in all of your controllers that increase the foundation controller class you have established, it defeats the purpose of extending the class.

To remedy this concern, you can consider edge of the HttpContext.RequestServices.GetService extension approach. Try to remember, the HttpContext instance will be null if you’re making an attempt to access it inside of the constructor of your controllers.

The services that are available as section of an ASP.Net Main ask for are accessible by means of the HttpContext.RequestServices assortment. This signifies that when you ask for a company, the ask for will be resolved from this assortment.

Include HttpContext to your foundation controller class in ASP.Net Main

Here’s the updated source code of our BaseController class.

public abstract class BaseController : ControllerBase wherever T : BaseController

  non-public ILogger _logger
  secured ILogger Logger => _logger ?? (_logger = HttpContext.RequestServices.GetService>())       

The OrderController class extends this abstract BaseController class as demonstrated in the code listing supplied beneath.

public class OrderController : BaseController
        non-public readonly IOrderManager _orderManager
        public OrderController(IOrderManager orderManager)
            _orderManager = orderManager
        public string Get()
            Logger.LogInformation("Hello Planet!")
            return "Inside the Get approach of OrderController"
        public void ProcessOrder(Purchase get)

And that’s it! The OrderController can leverage the Logger instance as perfectly as consider edge of constructor injection to inject other services.

Ultimately, keep in mind to sign-up your services in the ConfigureServices approach of your Startup class as demonstrated beneath.

public void ConfigureServices(IServiceCollection services)

It would be very best to resolve dependencies using a parameterized constructor, i.e., by using constructor injection. This will assistance you produce lessons that are much easier to test and much easier to preserve.

Copyright © 2021 IDG Communications, Inc.

Maria J. Danford

Next Post

What is devops? Transforming software development, explained

Thu Jun 24 , 2021
Devops is a person of the defining technological know-how marketplace developments of the previous decade, mainly for the reason that it bridges so quite a few of the improvements that have formed modern day application improvement. From the popularization of cloud infrastructure to agile improvement and cloud-indigenous computing, devops has […]

You May Like