Dependency Injection in .NET Core
Dependency injection is a software design pattern that is used to develop software with loosely coupled code. Dependency injection is a great technique to reduce the tight coupling between software components also it better maintainability and manage future changes and other complexity very easily.
Let’s look into an example of dependency injection,
ProductController.cs
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using DIExample.Models;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;namespace DIExample.Controllers{[ApiController][Route(“[controller]”)]public class ProductController : ControllerBase{private readonly IProductDetails _productDetails;public ProductController(IProductDetails productDetails){_productDetails = productDetails;}public string Index(){return _productDetails.GetProduct();}}}
ProductDetails.cs
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace DIExample.Models{public class ProductDetails : IProductDetails{public string GetProduct(){return “TestProduct”;}}}
IProductDetails.cs
namespace DIExample.Models{public interface IProductDetails{string GetProduct();}}
Here,
- ProductController is dependent on IProductDetails for retrieving data of products.
- Instead of creating a new instance of an implementation of IProductDetails, we are injecting IProductDetails instance into the ProductController using the constructor.
- This is called constructor injection, as we are using the constructor to inject the dependency.
- Notice, we are assigning the injected dependency to the private read-only field this is good practice as it prevents accidentally assigning another value inside a method.
- At this point when you run your project you will end up with getting the following exception,
‘’InvalidOperationException: Unable to resolve service for type DIExample.Models.IProductDetails’ while attempting to activate ‘DIExample.Controllers.ProductController’.’’ this is because DI container doesn’t know which object to provide if some requests and object that implements IProductDetails.
To resolve this problem we need to register the ProductDetails class on DI container we do this ConfigureService() method of the startup class
public void ConfigureServices(IServiceCollection services){services.AddControllers();services.AddSingleton<IProductDetails, ProductDetails>();}
There are different ways you can register your service on DI Container let’s look into these types below,
These methods are classified as per the lifetime of registered service.
AddSingleton() — AddSingleton() method creates a Singleton service. A Singleton service is created when it is first requested. This same instance is then used by all the subsequent requests it means one instance created per application and the same instance is used throughout the application.
AddTransient() — AddTransient() method creates a new instance of a Transient service each time it is requested.
AddScoped() — This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application, it creates 1 instance per each HTTP request but uses the same instance in the other calls within that same web request.
Advantages of Dependency Injection:
- Reduces class coupling
- Increases code reusability
- Improves code maintainability
- Make unit testing possible
Thank You, See you in the next article !!
You can reach out to me here,
LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar
Email: vaibhavbhapkar.medium@gmail.com