Wednesday, November 22, 2023

ASP.NET Core 8.0: Keyed Services in Dependency Injection

There are often times that we have different implementations of an interface and we need to resolve a particular implementation when doing dependency injection.

With ASP.NET Core 8.0, we now have support for Keyed Services.

Consider the following interface and its implementations.
public interface IMyService
    string GetValue();

public class MyService1 : IMyService
    public string GetValue() => "MyService1";

public class MyService2 : IMyService
    public string GetValue() => "MyService2";
Now we can register these Services with keys as follows.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddKeyedScoped<IMyService, MyService1>("service1");
builder.Services.AddKeyedScoped<IMyService, MyService2>("service2");
You can register Keyed services with other lifetimes as well (Transient and Singleton).

Now we can resolve a specific implementation by key using [FromKeyedServices] attribute.

From the constructor
// Note:
//    I am using Primary Constructor which is new with .NET 8.0
//    You can use the other constructor as well

public class MyClass([FromKeyedServices("service1")] IMyService myService)
    public string GetValue() => myService.GetValue();
From an API Endpoint
app.MapGet("/", ([FromKeyedServices("service2")] IMyService myService) =>
    return myService.GetValue();
Hope this helps.

Happy Coding.


No comments:

Post a Comment