Differences between TryAddEnumerable and TryAddTransient methods in. Net Core dependency Injection,
. Net Core, each service added by dependency injection, is eventually converted into a ServiceDescriptor instance. ServiceDescriptor contains the following attributes:
Lifetime: Service Life Cycle (Singleton: Singleton, Scoped: Transient: Temporary during a single request, create an instance each time)
ServiceType: service type
ImplementationType: service implementation type
ImplementationInstance: Implementation type instance
TryAddEnumerable and TryAddTransient are both used to add services, but they are not based on different filtering conditions.
TryAddEnumerable is determined based on the ServiceType and ImplementationType of the service when it is added. If a corresponding service already exists, it is not added. It is applicable to scenarios where multiple implementations are added for the same service, the source code is as follows:
if (!services.Any(d => d.ServiceType == descriptor.ServiceType && d.GetImplementationType() == implementationType)) { services.Add(descriptor); }
TryAddTransient is only determined based on the ServiceType of the service when it is added. If this type of service already exists, it is not added. This method is applicable to scenarios where the existing service of the same service is not added, the source code is as follows:
if (!collection.Any(d => d.ServiceType == descriptor.ServiceType)) { collection.Add(descriptor); }