Sometimes, the same service is registered in the ASP.NET Core dependency injection system. Sometimes by carelessness, sometimes by registering the instance yourself correctly, then a second time with automatic registration by scanning the assemblies. In my previous article here: http://anthonygiretti.com/2020/01/20/remove-unwanted-instances-from-servicecollection-in-asp-net-core-3-1/, I showed how to unregister services, in this article I will show how to detect multiple registrations when starting the application.
Check and log in action
In order to have a clean Startup.cs file, I won’t write any code there.
First we need to find multiple registrations by scanning all services.
I added a filter that ignores Microsoft’s assemblies, because some of them are registered several times automatically, like their ILogger. That scan registers in a static variable a collection of IGrouping objects that have in Key the type (fullName) of the service and a collection of ServiceDescriptor (registrations) corresponding to that service. Then I create an implementation of ConfigureServices() as an extension method on IHostBuilder.
Once done, after any registration, so just before the server starts, I will iterate on the collection of descriptors and log in the console each them with a message that warns the developer. To ensure that, I need to access to a ILogger instance from IServiceProvider, that’s why I will build an extension method on IHost that provides IServiceProvider.
Usage in Program.cs:
As you can see the ConfigureServiceDescriptionCheck method provides me the possibility to scan the ServiceCollection and UseServiceDescriptionCheck to access to a logger instance after any service registration and before server start.
Thanks for reading! 😉