CSC378 ยท 2080 ยท 5 marks
Mention the two types of services managed by IoC container and how they are registered?
Mention the two types of services managed by IoC container and how they are registered? [5]
Quick answer
NET Core supports three kinds of service lifetimes, of which the two most commonly highlighted types are: The IoC container creates and shares a single instance of a service throughout the application's lifetime; The instance is created the first time it is requested, and every subsequent request uses that same...
Two Types of Services Managed by IoC Container and Their Registration
Types of Services (Lifetimes)
The built-in IoC container in ASP.NET Core supports three kinds of service lifetimes, of which the two most commonly highlighted types are:
1. Singleton
- The IoC container creates and shares a single instance of a service throughout the application's lifetime.
- The instance is created the first time it is requested, and every subsequent request uses that same instance.
- Suitable for services that maintain global state or are expensive to create.
2. Transient
- The IoC container creates a new instance of the specified service type every time it is requested.
- This lifetime works best for lightweight, stateless services.
- Each request gets a completely fresh object.
3. Scoped (also managed by IoC)
- The IoC container creates one instance per HTTP request.
- The same instance is shared within a single request but a different instance is created for different requests.
How Services Are Registered
Services are registered inside the ConfigureServices method using the IServiceCollection interface. Registration is done using ServiceDescriptor:
public void ConfigureServices(IServiceCollection services)
{
// Singleton registration
services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));
// Transient registration
services.Add(new ServiceDescriptor(
typeof(ILog),
typeof(MyConsoleLogger),
ServiceLifetime.Transient));
// Scoped registration
services.Add(new ServiceDescriptor(
typeof(ILog),
typeof(MyConsoleLogger),
ServiceLifetime.Scoped));
}
Summary Table
| Lifetime | Instance Created | Shared? |
|---|---|---|
| Singleton | Once (first request) | Across entire application |
| Transient | Every request | Not shared |
| Scoped | Once per HTTP request | Within the same request only |
Once registered, the IoC container automatically performs constructor injection wherever the service type is used as a constructor parameter.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.