In .Net Dependency Injection is one of the most used concepts for increasing application performance and maintainability, In this article we will focus and the functionality of Dependency Injection.
What is Object Oriented Programming
Object Oriented Programming (OOP) provides developers with an organized, scalable, and easier way to write code for their projects. Developers create classes and objects to bifurcate their code into different files, keeping their program flow clean and debugable we talk about classes and objects so classes are a blueprint or template for creating objects and objects are the instances of the classes.
What is constructor
When we create a class in OOP, we provide a constructor, basically the initial argument required for the class.
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
// Custom constructor
public Car(string make, string model)
{
Make = make;
Model = model;
}
public void Start()
{
Console.WriteLine($"{Make} {Model} is starting...");
}
}
Car myCar = new Car("Toyota", "Camry");
myCar.Start();
myCar is the object of the class Car and the constructor is required to know about the maker and model of the car.
What is a Dependency Injection And Its Type?
Dependency Injection is a technique through which programmers can achieve the inversion of control (IoC) making the application maintainable and scalable. Dependency Injection is used by supplying the class from outside the working class rather than creating a new one.
AddTransient
AddTransient creates a new instance of the service on each request. It can be a good approach when your application requires stateless operations.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register INotificationService with EmailNotificationService implementation
services.AddTransient<INotificationService, EmailNotificationService>();
}
}
public class OrderService
{
private readonly INotificationService _notificationService;
// Constructor Injection
public OrderService(INotificationService notificationService)
{
_notificationService = notificationService;
}
public void PlaceOrder()
{
Console.WriteLine("Order placed successfully!");
_notificationService.Send("Order confirmation email sent.");
}
}
In the above code, we have added a transient service to the IServiceCollecition in which we have to bind the INotifcationService with EmailNotificationService by which whenever INotificationService is called EmailNotificationService instance will be provided as in the OrderService class constructor we have injected the INotificationService which will get an new instance of the EmailNotificationService.
AddSingleton
AddSingleton creates an instance of the class when the application starts. The instance of the class is shared with all the requests.
public interface ILoggerService
{
void Log(string message);
}
public class ConsoleLoggerService : ILoggerService
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Registering ConsoleLoggerService as a singleton
services.AddSingleton<ILoggerService, ConsoleLoggerService>();
}
}
In the code above we have created the ILoggerService for logging all the messages from the class, In this example we don’t require a new instance of the class on each request as the method will log all the messages that are given to it from anywhere.
AddScoped
AddScoped creates an instance once per request for example a customer comes to my website and wants to authenticate himself and use some of my services in the application because I do not want to reauthenticate him after going to every new service, so I will keep his details in authenticator service until the request is completed.
public interface IOrderService
{
void ProcessOrder();
}
public class OrderService : IOrderService
{
public void ProcessOrder()
{
Console.WriteLine("Processing order...");
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Registering OrderService as a scoped service
services.AddScoped<IOrderService, OrderService>();
}
}
In the code above an instance of OrderService is created for each request. With each request, users are authenticated as orders vary for each user. First, he will be authenticated then in the Authenticate Service Class I will have his details until the request is completed, and then this procedure will be restarted. As with new requests new authentication is required to get the specific user’s orders.
In conclusion, dependency injection is an essential concept to understand to master the application performance. To learn more about Dependency Injection. To check our other articles on .Net please visit here.