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;
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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…