In Focus

Dependency Injection In .NET Core

In this article, we will see how dependency injection works in .net core using Microsoft.Extension.DependencyInjection.

Consider a scenario where you want to fetch all the categories from the database and want to show that in the UI layer. So, you will create a service, i.e., a Web API which will be called by the UI layer. Now, in API, we need to create one GET method which will call the repository and the repository talks with the database. In order to call the repository, we need to create an instance of the same in API GET method, which means, it’s mandatory to create an instance of the repository for API. We can say the instance of the repository is the dependency of API. Now, let’s see how we can inject this dependency in our core Web API.

Open Visual Studio and create a new project

Select API as template and press OK.

Dependency Injection In .NET Core 

As we are going to fetch the categories, let’s create a category model which has two fields - CategoryId and CategoryName.

  1. namespace DIinCore  
  2. {  
  3.     public class Category  
  4.     {  
  5.         public int CategoryId { getset; }  
  6.         public string CategoryName { getset; }  
  7.     }  
  8. }  

Create an interface of repository having GetCategories method which returns the list of category object.

  1. using System.Collections.Generic;  
  2.   
  3. namespace DIinCore  
  4. {  
  5.     public interface ICategoryRepository  
  6.     {  
  7.         List<Category> GetCategories();  
  8.     }  
  9. }  

Implement the preceding interface and return some sample data. As our target is to understand dependency injection, here, we are not going to fetch the data from database rather returning hard coded ones.

  1. using System.Collections.Generic;  
  2. namespace DIinCore  
  3. {  
  4.     public class CategoryRepository : ICategoryRepository  
  5.     {  
  6.         public List<Category> GetCategories()  
  7.         {  
  8.             List<Category> categories = new List<Category>();  
  9.   
  10.             Category category = new Category() { CategoryId = 1, CategoryName = "Category1" };  
  11.             categories.Add(category);  
  12.   
  13.             category = new Category() { CategoryId = 2, CategoryName = "Category2" };  
  14.             categories.Add(category);  
  15.   
  16.             return categories;  
  17.         }  
  18.     }  
  19. }  

Assume that we are not aware of the dependency injection. Then, how will we expose the GET method from API? We used to create an instance of CategoryRepository and call the GetCategories method using that instance. So tomorrow, if there is a change in CategoryRepository it will directly affect the GET method of API as it is tightly coupled with that.

  1. [HttpGet]  
  2.         public async Task<IActionResult> Get()  
  3.         {  
  4.             CategoryRepository categoryRepository = new CategoryRepository();  
  5.             List<Category> categories = categoryRepository.GetCategories();  
  6.   
  7.             return Ok(categories);  
  8.         }  

With the .NET Framework, we used to use containers like LightInject, NInject, Unity etc. But in .NET Core, Microsoft has provided an in-built container. 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. Also, we can mention which kind of instance we want to inject - the lifetime of our instance.

Transient

It creates an instance each time they are requested and are never shared. It is used mainly for lightweight stateless services.

Singleton

This creates only single instances which are shared among all components that require it.

Scoped

It creates an instance once per scope which is created on every request to the application.

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. namespace DIinCore  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         public Startup(IConfiguration configuration)  
  11.         {  
  12.             Configuration = configuration;  
  13.         }  
  14.   
  15.         public IConfiguration Configuration { get; }  
  16.   
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.             //services.AddTransient<ICategoryRepository, CategoryRepository>();  
  20.   
  21.             services.AddSingleton<ICategoryRepository, CategoryRepository>();  
  22.   
  23.             //services.AddScoped<ICategoryRepository, CategoryRepository>();  
  24.   
  25.             services.AddMvc();  
  26.         }  
  27.   
  28.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  29.         {  
  30.             if (env.IsDevelopment())  
  31.             {  
  32.                 app.UseDeveloperExceptionPage();  
  33.             }  
  34.   
  35.             app.UseMvc();  
  36.         }  
  37.     }  
  38. }  

So far, we have added our dependency to the collection. Now, it’s time to inject where we need it, i.e., in the Web API. Our GET method is inside the CategoryController and we want an instance of categoryrepository. So, let’s create a constructor of CategoryController which expects the type of ICategoryRepository. From this parameterized constructor, set the private property of type ICategoryRepository which will be used to call GetCategories from the GET method.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using System.Collections.Generic;  
  3. using System.Threading.Tasks;  
  4.   
  5. namespace DIinCore.Controllers  
  6. {  
  7.     [Route("api/Category")]  
  8.     public class CategoryController : Controller  
  9.     {  
  10.         private ICategoryRepository categoryRepository { getset; }  
  11.         public CategoryController(ICategoryRepository categoryRepository)  
  12.         {  
  13.             this.categoryRepository = categoryRepository;  
  14.         }  
  15.   
  16.         [HttpGet]  
  17.         public async Task<IActionResult> Get()  
  18.         {  
  19.             List<Category> categories = categoryRepository.GetCategories();  
  20.             return Ok(categories);  
  21.         }  
  22.     }  
  23. }  

Run the application and we will be able to see the result of the GET method of CategoryController. Now, even though we haven’t created an instance of CategoryRepository which is expected by CategoryController, we are able to call the GET method successfully. The instance of CategoryRepository has been resolved dynamically, i.e., our Dependency Injection.

Dependency Injection In .NET Core 

You can download the sample code from here.