It is way too hot today to write a long post, so I focus on a small but useful new feature in .NET 6.
As I mentioned before in most of my projects I'm using Autofac as the Inversion of Control container of my choice. One of the features that Autofac has to offer is the IsRegistered
method which allows you to check if a specific type is already registered in the IoC container.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool isRegistered=container.IsRegistered<IExampleInterface>>(); |
Starting from .NET 6, you can do a similar thing with the Microsoft DI container using the IServiceProviderIsService
interface:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public partial interface IServiceProviderIsService | |
{ | |
bool IsService(Type serviceType); | |
} |
You first need to resolve the interface from the container and then you can call the IsService()
method to see if the service can be resolved through the container or not:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var serviceProviderIsService = container.GetService<IServiceProviderIsService>(); | |
var isRegistered=serviceProviderIsService.IsService(typeof(IExampleInterface))); |
That’s it! Time to cool down(literally)…