What is Service Lifetime in C#: Explanation and Examples
service lifetime defines how long an instance of a service is kept when using dependency injection. It controls whether a service is created once and shared (Singleton), created per scope like a web request (Scoped), or created every time it is requested (Transient).How It Works
Imagine you have a coffee machine in an office. If the machine is shared by everyone all day, that's like a Singleton service lifetime — one instance used everywhere. If each team gets its own coffee machine for the day, that’s like a Scoped lifetime — one instance per team (or scope). If every person brings their own small coffee maker every time they want coffee, that’s like Transient — a new instance each time.
In C# dependency injection, service lifetime controls how long the system keeps a service instance before making a new one. This helps manage resources and behavior, like sharing data or keeping things fresh.
Choosing the right lifetime ensures your app runs efficiently and behaves as expected, especially in web apps where requests create scopes.
Example
This example shows how to register services with different lifetimes and how they behave when requested multiple times.
using System; using Microsoft.Extensions.DependencyInjection; public interface IService { Guid GetId(); } public class MyService : IService { private Guid _id = Guid.NewGuid(); public Guid GetId() => _id; } class Program { static void Main() { var services = new ServiceCollection(); services.AddSingleton<IService, MyService>(); var providerSingleton = services.BuildServiceProvider(); var s1 = providerSingleton.GetService<IService>(); var s2 = providerSingleton.GetService<IService>(); Console.WriteLine($"Singleton IDs: {s1.GetId()} and {s2.GetId()}"); services = new ServiceCollection(); services.AddTransient<IService, MyService>(); var providerTransient = services.BuildServiceProvider(); var t1 = providerTransient.GetService<IService>(); var t2 = providerTransient.GetService<IService>(); Console.WriteLine($"Transient IDs: {t1.GetId()} and {t2.GetId()}"); } }
When to Use
Use Singleton when you want one shared instance for the entire app lifetime, like a configuration service or a cache. This saves memory and keeps data consistent.
Use Scoped in web apps to create one instance per user request or operation, such as database contexts. This keeps data isolated per request and avoids conflicts.
Use Transient when you need a fresh instance every time, like lightweight services that don’t hold state or when you want to avoid shared data.
Choosing the right lifetime helps your app be efficient, safe, and easy to maintain.
Key Points
- Singleton: One instance for the whole app.
- Scoped: One instance per scope, often per web request.
- Transient: New instance every time requested.
- Service lifetime affects resource use and data sharing.
- Pick lifetime based on how long you want to keep service data.