CodeBlanks Logo Icon CodeBlanks

Lifetime: Scoped and Transient

C# course · Advanced · Lesson 59/83

Learn Scoped and Transient lifetimes.

Scoped and Transient

Transient: each resolve yields a new instance. It suits lightweight, stateless services. Scoped: one instance per scope; in web applications a scope is usually one request.

You open a scope with provider.CreateScope(); resolves within the same scope share the same scoped instance. Different scopes get different scoped instances. This is ideal for services that need consistent state per request.

CreateScope

provider.CreateScope() opens a new scope. GetRequiredService calls within the same scope return the same instance for scoped services. When the scope is disposed, the scoped instances in it are disposed too.

In web applications each request is a scope; when the request ends, the scope closes and instances are cleaned up. This is critical for per-request consistent resources like a database context. In console apps you open and close scopes manually.

Exercise Transient: verify different instances

In Main, create the container with var services = new ServiceCollection();. Register Marker as transient with services.AddTransient<Marker>();. Build the provider with var provider = services.BuildServiceProvider();. Resolve twice with var m1 = provider.GetRequiredService<Marker>(); and var m2 = provider.GetRequiredService<Marker>();. Set m1.Id = 100; and print Console.WriteLine(m2.Id);.

Show example solution
var services = new ServiceCollection(); services.AddTransient<Marker>(); var provider = services.BuildServiceProvider(); var m1 = provider.GetRequiredService<Marker>(); var m2 = provider.GetRequiredService<Marker>(); m1.Id = 100; Console.WriteLine(m2.Id);
Example solution:
using System;
using Microsoft.Extensions.DependencyInjection;

class Marker
{
    public int Id { get; set; }
}

class Program
{
    static void Main()
    {
        var services = new ServiceCollection();
        services.AddTransient<Marker>();
        var provider = services.BuildServiceProvider();
        var m1 = provider.GetRequiredService<Marker>();
        var m2 = provider.GetRequiredService<Marker>();
        m1.Id = 100;
        Console.WriteLine(m2.Id);
    }
}

Test yourself

  1. Complete the Transient registration

    services.Add____<ILogger, ConsoleLogger>();
    Show answer
    services.AddTransient<ILogger, ConsoleLogger>();
  2. What does Transient return on each GetService call?

    • The same instance
    • A new instance
    • Null
    • Only a static instance
    Show answer

    A new instance — Correct. Transient returns a new instance on each call.

  3. Match the lifetime to its scope behavior

    Transient
    New per call
    Scoped
    Single in scope
    Singleton
    Single in app
    CreateScope
    Opens a new scope

All lessons in Advanced