Debugging Dependency Injection Service Registrations in .NET 5.0

Investigating a technique on how to debug service registrations when functionality isn't working as expected.

Published on 12 January 2021


Dependency Injection is everywhere in modern development. It won't solve all your problems and there is a time and place to use it. However if you are working in .NET 5.0 and ASP.NET 5.0 then using it makes life a lot smoother.

At times you may come across unusual functionality and wonder why. This is one way to help diagnose the issue.


You've got your services registered as before in our previous example.

var services = new ServiceCollection();
services.AddTransient<ISayHello, SayHello>();

And then someone adds in another service without you knowing. This might be through another extension method, adding another package or a corrupt merge.

services.AddTransient<ISayHello, NewHello>();

You have a service which depends on ISayHello and all of a sudden functionality has changed. How do we determine the issue?

The trick is to update the constructor signature of the service in question from the required setup to a debug constructor, from ...

public MyService(ISayHello sayHello)
    _sayHello = sayHello;

... to ...

public MyService(IEnumerable<ISayHello> sayHello)


This will allow for you to debug the service construction. What is this doing? This is telling the IOC container that to construct an instance of this service it wants all of the ISayHello service registrations as an IEnumerable<>. This will allow you to put a break point in the constructor of this service and run the application ad see all of the service registrations for the target type. This should inject the target services in the order in which they are registered do will allow for further investigation as to where the issue has manifested itself.


In this post we have seen how to debug a dependency injection multiple service registraton issue. Multiple registrations can happen and using Add* methods will add them into the collection no matter what. If you want to add a registration only if there hasn't already been one then investigating the TryAdd* extension methods is what you need.

Let me know on Twitter @WestDiscGolf if this tip was helpful.