SHARE:

Check and log multiple registrations of a same service in ASP.NET Core 3.1

Introduction

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.

I will write extensions methods that will be used on IHostBuilder and IHost instances in Program.cs.

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.

Code:

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.

Demo:

Thanks for reading! 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: