Remove unwanted instances from ServiceCollection in ASP.NET Core 3.1
Introduction
At first glance this article sounds strange or has no sense. Well, this is wrong because it’s based on an unfortunate experience of recent times. I recently had the following experience: I was developing my Web API without too much pain until the moment when I discovered an unexpected behavior, I realized that one of my services did not have the desired behavior , and I discovered that its interface was registered with another instance than the one I coded for my Web API. This could have happened because I reused a legacy layer and I used an extension method which allows to automatically register instances by scanning the assemblies of my application. I am writing this article in order to show you how I managed to solve my problem other than simply renaming my interface, by simply deleting the registration of my service in the dependency injection container. This article will go a little further, I will show you how to unregister any type of service.
Unregister any type of service
To make it work we need to find in the collection of registered services (IServiceCollection) the definition of the registered service. That definition contains the ServiceType (interface), the ImplementationType and the Lifetime of the service. All that information are stored in an object named ServiceDescriptor.
Sometimes a service is registered without any interface, as DbContext as well. No problem! ServiceType is not necessarily the interface’s type, ServiceType is filled with the ImplementationType when no interface is registered. So we can easily find our registration.
once the descriptor is found in the collection, the IServiceCollection interface provides a method named Remove() to remove the descriptor.
Examples of:
- A service with its interface
- A DbContext without any interface
- An HttpClient with its interface only
- An HttpClient without any interface
- A Refit client with only its interface
Remove() method returns a boolean, so you can check if it returns true if the removal succeed, false if not.
That’s it! Hope this article will help you 🙂