Sobes.tech
Middle

What is transient in the context of C#?

sobes.tech AI

Answer from AI

In the context of C#, the keyword transient is not part of the language syntax. It likely refers to the concept of Transient Lifetime in dependency injection (DI) containers).

With Transient Lifetime, each time a service instance is requested, the DI container creates a new instance of that class.

Features of Transient Lifetime:

  • New instance on each request: Isolates service usage, preventing unwanted side effects between different consumers.
  • High overhead: Creation and destruction of objects happen more frequently.
  • Suitable for lightweight, stateless services: Where there is no need to maintain state between calls.

Example of registering a Transient service in .NET Core/5+:

// In the ConfigureServices method of the Startup class
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyService, MyService>();
}

Comparison of Lifetime Scopes (Transient, Scoped, Singleton):

Lifetime Scope Description When used
Transient A new instance is created on each service request. For lightweight, stateless services.
Scoped A new instance is created once per scope lifetime (e.g., per HTTP request). For services tied to a specific context (e.g., database context).
Singleton The same instance is used throughout the application's lifetime after the first request. For services requiring state sharing or expensive initialization.
What is transient in the context of C#? — C# - sobes.tech