The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
AddKeyedTransient is a
dependency injection (DI) registration method in ASP.NET Core that lets you register
multiple implementations of the same service type, each identified by a
key. It was introduced in .NET 8 as part of the new keyed services feature.
Unlike AddTransient, which registers a single implementation (or multiple without an easy way to distinguish them),
AddKeyedTransient allows you to resolve a specific implementation using a unique key such as a string, enum, or other object.
You can inject a specific implementation using the [FromKeyedServices] attribute.
public class NotificationController : ControllerBase
{
private readonly IMessageService _messageService;
public NotificationController(
[FromKeyedServices("email")] IMessageService messageService)
{
_messageService = messageService;
}
}
Example
Interface
public interface IMessageService
{
void Send(string message);
}
Implementations
public class EmailService : IMessageService
{
public void Send(string message)
{
Console.WriteLine($"Email: {message}");
}
}
public class SmsService : IMessageService
{
public void Send(string message)
{
Console.WriteLine($"SMS: {message}");
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
AddKeyedTransientis a dependency injection (DI) registration method in ASP.NET Core that lets you register multiple implementations of the same service type, each identified by a key. It was introduced in .NET 8 as part of the new keyed services feature.Unlike
AddTransient, which registers a single implementation (or multiple without an easy way to distinguish them),AddKeyedTransientallows you to resolve a specific implementation using a unique key such as a string, enum, or other object.Syntax
Resolving a Keyed Service
You can inject a specific implementation using the
[FromKeyedServices]attribute.Example
Interface
Implementations
Registration
Injection
Lifetime
AddKeyedTransientcreates a new instance every time the keyed service is requested, just likeAddTransient.When to Use
AddKeyedTransientswitchstatements.Comparison
AddTransientAddKeyedTransientAddScopedAddKeyedScopedAddSingletonAddKeyedSingleton