[FromKeyedServices] Another approach of DI on controllers constructor

Author:

Since .NET 8 the annotation [FromKeyedServices] comes to show a new approach of dependency injection.

With this annotation, we wouldn’t have to face a constructor the tons of interfaces.

The usage of this feature is towards controllers only.

Let’s make a comparison of show it works.

Example

The usual Dependency Injection

First, let me bring something usual, this is what you probably face during your daily-basis

This a controller getting interfaces references through DI.

Changes on Program.cs

In order to achieve the usage of [FromKeyedServices] we must change Program.cs like the way below:

Now, it’s time to get rid of the constructor, each action (endpoint) will get injection based on the key.

Pay attention at the difference between before and after.

So you can see, there’s no constructor at all. Now, the dependency injection takes place at endpoint level, letting us having a clean controller with actions only.

This is a really cool feature as from now we are not going to need huge constructor with many Interfaces.

Conclusion

I would say if you have a .NET 8 project with traditional controllers to go ahead with this approach, it will give you a clean code on controllers.

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *