Reputation: 641
I am creating helper classes to simplify configuration and injection of interfaces via IServiceCollection
for a library. The libraries constructor contains a number of dependencies that are likely to have been injected earlier. If they aren't already inserted into IServiceCollection
, the helper class should add them. How do I detect if the interface has already been injected?
public static void AddClassLibrary(this IServiceCollection services
, IConfiguration configuration)
{
//Constructor for ClassLibrary requires LibraryConfig and IClass2 to be in place
//TODO: check IServiceCollection to see if IClass2 is already in the collection.
//if not, add call helper class to add IClass2 to collection.
//How do I check to see if IClass2 is already in the collection?
services.ConfigurePOCO<LibraryConfig>(configuration.GetSection("ConfigSection"));
services.AddScoped<IClass1, ClassLibrary>();
}
Upvotes: 64
Views: 30117
Reputation: 56909
Microsoft has included extension methods to prevent services from being added if they already exist. For example:
// services.Count == 117
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118
To use them, you need to add this using directive:
using Microsoft.Extensions.DependencyInjection.Extensions;
NOTE: If that isn't visible, you may need to install the Microsoft.Extensions.DependencyInjection.Abstractions NuGet package.
If the built-in methods don't meet your needs, you can check whether or not a service exists by checking for its ServiceType
.
if (!services.Any(x => x.ServiceType == typeof(IClass1)))
{
// Service doesn't exist, do something
}
Upvotes: 141