How to determine if service has already been added to IServiceCollection

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
}

Leave a Comment