Dependency Injection in C#
Dependency Injection (DI) is a powerful concept in software development, particularly in C#. It is a technique where one object supplies the dependencies of another object, rather than the object creating its dependencies. This approach enhances the modularity, testability, and maintainability of your code.
In the context of DI, you will use three terms when registering services with your DI container: Singleton, Transient, and Scoped. Let’s break down each of these:
1. Singleton
Singleton means the DI container will create and share a single service instance throughout the application’s lifetime. Every time the service is requested, the same instance will be returned. This is useful for stateless services or services that are expensive to create.
Example:
services.AddSingleton<IRandomNumberGenerator, RandomNumberGenerator>();
2. Transient
Transient services are created each time they’re requested. This means that every time you ask the DI container for an instance of a transient service, it creates a new instance for you. Transient services are typically used for lightweight, stateless services.
Example:
services.AddTransient<IRandomNumberGenerator, RandomNumberGenerator>();
3. Scoped
Scoped services are created once per request (or per scope) and are shared within that scope. In a web application, for instance, a scoped service would be created once per HTTP request and would be shared across all components involved in processing that request.
Example:
services.AddScoped<IRandomNumberGenerator, RandomNumberGenerator>();
Let us create a detailed example in a simple console application to demonstrate Singleton, Transient, and Scoped lifetimes in C# using Dependency Injection.
- Create a new console application using .NET CLI or Visual Studio.
- Add the
Microsoft.Extensions.DependencyInjection
package to your project. - Define the services by adding the interface methods and their implementations.
4. Configure the services in the Main
method.
5. Output in console
Here are the key definitions related to Dependency Injection in C#
- Singleton: This will create only one class instance, which will be used everywhere.
- Transient: This will create a new instance of the class every time it is injected.
- Scoped: Within a single request, the same instance will be used wherever it is injected. However, once the request ends, those instances will be disposed of.
GitHub Repository
You can find the sample code for demonstrating Singleton, Transient, and Scoped lifetimes in a console application at the following GitHub repository: