Welcome to our in-depth tutorial on Dependency Injection Lifetimes in ASP .NET! This lesson is designed for both beginners and intermediate learners, so let's get started! 📝
Dependency Injection is a design pattern that helps manage dependencies between classes, improving code modularity and testability. It allows us to provide objects to dependencies of a class, rather than the class creating or managing them directly.
Dependency Injection Lifetimes determine how long an object instance stays in memory. In ASP .NET, there are four main lifetime types:
Singleton: A single instance of the object is created and reused throughout the application.
Transient: A new instance of the object is created every time it is requested.
Scoped: Object instances are specific to the current operation, such as a request in ASP .NET.
Instance Per Dependency: An instance of the object is created when a dependency on it is first resolved.
To implement Dependency Injection in ASP .NET, we'll use the built-in IServiceCollection and IServiceProvider classes. Let's dive into an example to understand it better.
public interface IMyService {
void DoSomething();
}
public class MyService : IMyService {
private readonly List<string> _logs = new List<string>();
public MyService() {
_logs.Add($"{nameof(MyService)} created.");
}
public void DoSomething() {
_logs.Add($"{nameof(MyService)} doing something.");
}
public void AddLog(string log) {
_logs.Add(log);
}
}
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton<IMyService, MyService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
// Access the Singleton service
var myService = app.ApplicationServices.GetService<IMyService>();
myService.DoSomething();
myService.AddLog("Request started.");
// Another instance of the service
var anotherService = app.ApplicationServices.GetService<IMyService>();
anotherService.DoSomething();
anotherService.AddLog("Another request.");
// Check if the services are the same instance
Console.WriteLine(Object.ReferenceEquals(myService, anotherService));
}In this example, we create an IMyService interface and a concrete implementation MyService. We then register the MyService as a Singleton using services.AddSingleton<IMyService, MyService>(). When we access the service using app.ApplicationServices.GetService<IMyService>(), we get the same instance every time.
What happens when you register a service as Singleton in ASP .NET?
We hope you found this tutorial helpful! Dependency Injection is a powerful tool that can greatly improve the structure and maintainability of your ASP .NET applications. Happy coding! 🎯💡📝