Transient

CustomService1 — a new instance on every resolution.

When to use: lightweight, stateless services. Each injection gets its own instance, even within the same request.

Where do the three IDs come from?

When this page loads, ASP.NET Core builds the page model by calling its constructor. The container resolves ICustomService twice in the page, and also injects SampleService. Because this service is transient, SampleService receives a new instance — different from both injections in the page.

Page constructor — TransientModel

public TransientModel(
    ICustomService firstInjection,    // parameter 1: first injection
    ICustomService secondInjection,   // parameter 2: second injection
    SampleService sampleService)      // parameter 3: via SampleService
{
    FirstInjectionId = firstInjection.InstanceId;
    SecondInjectionId = secondInjection.InstanceId;
    SampleServiceId = sampleService.CustomService.InstanceId;
}

SampleService constructor

public SampleService(
    ICustomService customService,
    ...)
{
    CustomService = customService;
}

// This page reads: sampleService.CustomService.InstanceId

Result in this request

Resolution Constructor parameter Instance ID
First injection firstInjection c4091015-da21-45ba-87d2-d161b1d3163b
Second injection secondInjection 8768e534-47b5-4a53-bdf7-994baabebd93
Via SampleService sampleService.CustomService ed5e2b78-aeff-4f46-8e37-1e1e45273fc6
Every resolution has a unique ID — exactly as shown in the diagram for GetTransientID (Sample Service and ITransientService differ).

Registration in Program.cs:

builder.Services.AddTransient<ICustomService, CustomService1>();

← Back to overview