4

.NET 8 Dependency Injection Changes: Keyed Services

 9 months ago
source link: https://weblogs.asp.net/ricardoperes/net-8-dependency-injection-changes-keyed-services
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

.NET 8 Dependency Injection Changes: Keyed Services

Wednesday, July 26, 2023

Keyed Services in .NET 8

It has been quite some time since my last post on dependency injection (DI). In it I tried to talk a bit about the history of DI (or dependency resolution); now, a change is about to come in .NET 8: named (or keyed) services! Essentially, it consists of the possibility to register multiple times the same type under different names, and to inject a specific type/name combo.

To make this possible, a new interface is introduced, IKeyedServiceProvider, which extends our old friend IServiceProvider with two new methods:

  • object? GetKeyedService(Type serviceType, object? serviceKey);
  • object GetRequiredKeyedService(Type serviceType, object? serviceKey);

I guess these are pretty straightforward. In order to register objects we have overloads that take keys on IServiceCollection, for example, for the singleton lifetime:

builder.Services.AddKeyedSingleton<IMyService, AService>("a");
builder.Services.AddKeyedSingleton<IMyService, BService>("b");

And to inject, we have a new attribute, [FromKeyedServices]:

public IActionResult Get([FromKeyedServices("a")] IMyService svc) { ... }

By default, if you pass an empty string as the key, you will get the default, no-key, implementation.

I think this is a great idea, as it gives you more flexibility: if you don't need it, by all means, don't use it, but if you do, hey, it's a great addition! Looking forward for .NET 8 to arrive!

No Comments

Add a Comment

Name

As it will appear on the website

Email

Not displayed

Url

Your website

Comment

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK