When functioning with controllers in world wide web applications applying ASP.Internet Core or ASP.Internet Core MVC, you may have encountered code redundancy. For case in point, you may have occur across controllers that use dependency injection (DI) to inject expert services that they want. If the code that injects the dependencies has been reused in many controllers, then you have code redundancy and violation of the DRY basic principle (never repeat oneself).

This short article seems to be at DI code redundancy and demonstrates how to create your custom base controller to stay away from these challenges. To do the job with the code examples delivered in this short article, you really should have Visual Studio 2019 put in in your method. If you never previously have a copy, you can down load Visual Studio 2019 in this article.

Produce an ASP.Internet Core MVC project in Visual Studio

To start with off, let us create an ASP.Internet Core project in Visual Studio 2019. Next these methods will create a new ASP.Internet Core MVC project in Visual Studio 2019.

  1. Start the Visual Studio IDE.
  2. Click on on “Create new project.”
  3. In the “Create new project” window, pick “ASP.Internet Core Net App (Product-Watch-Controller)” from the list of templates exhibited.
  4. Click on Subsequent.
  5. In the “Configure your new project” window, specify the title and place for the new project.
  6. Optionally check the “Place answer and project in the exact same directory” check box, based on your preferences.
  7. Click on Subsequent.
  8. In the “Additional Information” window shown upcoming, pick .Internet 5. as the focus on framework from the drop-down list at the prime. Depart the “Authentication Type” as “None” (default).
  9. Make sure that the check containers “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we will not be applying any of those people options in this article.
  10. Click on Produce.

A new ASP.Internet Core MVC project will be designed. We’ll use this project to do the job with dependency injection in the subsequent sections of this short article.

Now observe the methods outlined under to create additional controllers in your project.

  1. Proper-click on the Controllers answer folder.
  2. Decide on Incorporate -> Controller.
  3. In the “Add New Scaffolded Item” dialog, pick API as the template (by default MVC will be chosen).
  4. Decide on the item “API Controller with read/publish actions.”
  5. Click on Incorporate.
  6. In the “Add New Item” dialog shown upcoming, specify a title for your new controller.
  7. Click on Incorporate.

Created-in base controller classes in ASP.Internet Core

There are two base classes for controllers, particularly ControllerBase and Controller. The ControllerBase class implements the IController interface and delivers the implementation for a number of methods and houses. It defines an abstract system named ExecuteCore that is used to identify the action system and execute it. You really should use ControllerBase any time you are making your APIs.

The Controller class extends the ControllerBase class, delivers the ExecuteCore system, and provides a number of methods you can use in your controller classes these as Watch() and Redirect(). Like ControllerBase, the Controller class is a base controller class with perspective help. As a result you really should use the Controller class any time you are developing your controllers in ASP.Internet Core MVC. The ControllerBase class delivers the needed integration with routing and HttpContext so that you can leverage them. It also incorporates the code demanded for controlling ViewData and TempData.

Put into practice a base controller class in ASP.Internet Core

When we create a new API controller class in ASP.Internet Core, it extends the ControllerBase class by default. Subsequent, we’ll create our implementation of a base controller. Our base controller class will prolong the ControllerBase class of the framework.

Here is an entity class we will be applying in this case in point:

public class Get
   
        public int Id get established
        public int CustomerId get established
        public string Tackle get established        
   

Now create the following interface termed IOrderManager that incorporates the declaration of a system named ProcessOrder.

public interface IOrderManager
   
        public void ProcessOrder(Get order)
   

Subsequent create the OrderManager class that extends the IOrderManager interface and implements its ProcessOrder system.

public class OrderManager : IOrderManager

   public void ProcessOrder(Get order)
  
      toss new Technique.NotImplementedException()
  

The following code listing demonstrates how you can create a base controller class by deriving it from the ControllerBase class.

[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

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

Increase your custom base controller in ASP.Internet Core

You can now create your controllers by deriving from this custom base controller we just designed. The following code listing illustrates how you can create your controller class by extending it from the newly designed base controller class.

[Route("api/[controller]")]
[ApiController]
public class OrderController : BaseController

   private readonly ILogger _logger
  [HttpGet]
   public string Get()
  
       return "OrderController"
  
   [HttpPost]
   public void ProcessOrder(Get order)
  
      _orderManager.ProcessOrder(order)
  

Nonetheless, you will uncover that the higher than code will not compile. Here is the error you will be introduced with in Visual Studio:

base controller class error IDG

The error states that you want to implement yet another argument constructor with the exact same arguments as the constructor of the BaseController class. But why? If you are going to replicate the dependency injection code in all of your controllers that prolong the base controller class you have designed, it defeats the intent of extending the class.

To clear up this issue, you can just take advantage of the HttpContext.RequestServices.GetService extension system. Keep in mind, the HttpContext instance will be null if you are attempting to entry it within the constructor of your controllers.

The expert services that are accessible as component of an ASP.Internet Core ask for are obtainable through the HttpContext.RequestServices collection. This signifies that when you ask for a provider, the ask for will be resolved from this collection.

Incorporate HttpContext to your base controller class in ASP.Internet Core

Here’s the up-to-date source code of our BaseController class.

public abstract class BaseController : ControllerBase where T : BaseController

  private ILogger _logger
  shielded ILogger Logger => _logger ?? (_logger = HttpContext.RequestServices.GetService>())       

The OrderController class extends this abstract BaseController class as shown in the code listing offered under.

[Route("api/[controller]")]
[ApiController]
public class OrderController : BaseController
   
        private readonly IOrderManager _orderManager
        public OrderController(IOrderManager orderManager)
       
            _orderManager = orderManager
       
        [HttpGet]
        public string Get()
       
            Logger.LogInformation("Hello there Earth!")
            return "Within the Get system of OrderController"
       
        [HttpPost]
        public void ProcessOrder(Get order)
       
            _orderManager.ProcessOrder(order)
       
   

And that’s it! The OrderController can leverage the Logger instance as nicely as just take advantage of constructor injection to inject other expert services.

At last, don’t forget to register your expert services in the ConfigureServices system of your Startup class as shown under.

public void ConfigureServices(IServiceCollection expert services)
       
            expert services.AddTransient()
            expert services.AddControllersWithViews()
       

It would be best to take care of dependencies applying a parameterized constructor, i.e., by applying constructor injection. This will enable you create classes that are simpler to examination and simpler to manage.

Copyright © 2021 IDG Communications, Inc.