October 18, 2023

.NET 8 Dependency Injection Keyed Services

In .NET 8, Inversion of Control (IOC) has been enhanced to support keyed services, enabling more nuanced dependency injection in application architectures. 

With keyed services, developers can associate specific keys with particular service implementations, granting more fine-grained control over service retrieval from the IOC container. This means that when a consumer requests a service, it can specify a key to receive a particular implementation of the service interface. 

This flexibility is crucial for scenarios where multiple implementations of an interface exist, and the decision to use one over another is determined at runtime. Keyed services in .NET 8’s IOC container therefore facilitate a more dynamic, adaptable, and modular application architecture. 

Here is a simple example of the Keyed services

Multiple implementation for the same interface 


public interface IGreetingService
{
string GetGreeting();
}

public class EnglishGreetingService : IGreetingService
{
public string GetGreeting() => "Hello!";
}

public class SpanishGreetingService : IGreetingService
{
public string GetGreeting() => "¡Hola!";
}

Register the implementation with a key

builder.Services.AddKeyedSingleton<IGreetingService, EnglishGreetingService>("English");
builder.Services.AddKeyedSingleton<IGreetingService, SpanishGreetingService>("Spanish");

Use the key to inject to the required functions


app.MapGet("/greet",
([FromKeyedServices("English")]IGreetingService english,
[FromKeyedServices("Spanish")]IGreetingService spanish) =>
$"English:{english.GetGreeting()} Spanish: {spanish.GetGreeting()}")
.WithName("GreetingEndpoint");

Hope this helps!

No comments: