Dependency injection in ASP.NET Core MVC controller explained step by step

ASP.NET Core MVC controllers should request their dependencies explicitly via their constructors. In some instances, individual controller actions may require a service, and it may not make sense to request at the controller level. In this case, you can also choose to inject a service as a parameter on the action method.

With ASP.NET 5 MVC6, we get a feature called dependency injection baked right into the framework for us.

Dependency injection is a technique that follows the Dependency Inversion Principle, allowing for applications to be composed of loosely coupled modules. ASP.NET Core has built-in support for dependency injection, which makes applications easier to test and maintain.

ASP.NET Core's built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that type using its built in service container. Services are typically, but not always, defined using interfaces. For example, if your application has business logic that depends on the current time, you can inject a service that retrieves the time (rather than hard-coding it), which would allow your tests to pass in implementations that use a set time.

 using System;  
 namespace ControllerDI.Interfaces  
 {  
   public interface IDateTime  
   {  
     DateTime Now { get; }  
   }  
 }  

Implementing an interface like this one so that it uses the system clock at runtime is trivial:

 using System;  
 using ControllerDI.Interfaces;  
 namespace ControllerDI.Services  
 {  
   public class SystemDateTime : IDateTime  
   {  
     public DateTime Now  
     {  
       get { return DateTime.Now; }  
     }  
   }  

With this in place, we can use the service in our controller. In this case, we have added some logic to the HomeControllerIndex method to display a greeting to the user based on the time of day.




 using ControllerDI.Interfaces;  
 using Microsoft.AspNetCore.Mvc;  
 namespace ControllerDI.Controllers  
 {  
   public class HomeController : Controller  
   {  
     private readonly IDateTime _dateTime;  
     public HomeController(IDateTime dateTime)  
     {  
       _dateTime = dateTime;  
     }  
     public IActionResult Index()  
     {  
       var serverTime = _dateTime.Now;  
       if (serverTime.Hour < 12)  
       {  
         ViewData["Message"] = "It's morning here - Good Morning!";  
       }  
       else if (serverTime.Hour < 17)  
       {  
         ViewData["Message"] = "It's afternoon here - Good Afternoon!";  
       }  
       else  
       {  
         ViewData["Message"] = "It's evening here - Good Evening!";  
       }  
       return View();  
     }  
   }  
 }  

we have to configured a service in the ConfigureServices method in our Startup class. To specify that requests for IDateTime should be resolved using an instance of SystemDateTime, add the highlighted line in the listing below to your ConfigureServices method:

 public void ConfigureServices(IServiceCollection services)  
 {  
   // Add application services.  
   services.AddTransient<IDateTime, SystemDateTime>();  
 }  

Once the service has been configured, running the application and navigating to the home page should display the time-based message as expected:

A message from server It's afternoon here - Good Afternoon! friend

Comments

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Restore the lost focus of Auto post back controls in asp.net update Panel control

Disable backspace key using Jquery