0
0
CsharpConceptBeginner · 4 min read

What is Service Lifetime in C#: Explanation and Examples

In C#, 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.

csharp
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()}");
    }
}
Output
Singleton IDs: 3f29a1e2-8b5a-4f1a-9c3a-2e7f9a1d4b6c and 3f29a1e2-8b5a-4f1a-9c3a-2e7f9a1d4b6c Transient IDs: 7a1c2d3e-4b5f-6a7b-8c9d-0e1f2a3b4c5d and 1b2c3d4e-5f6a-7b8c-9d0e-1f2a3b4c5d6e
🎯

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.

Key Takeaways

Service lifetime controls how long a service instance lives in C# dependency injection.
Singleton shares one instance across the entire app lifetime.
Scoped creates one instance per scope, like a web request.
Transient creates a new instance every time it is requested.
Choosing the right lifetime improves app performance and behavior.