Differences between TryAddEnumerable and TryAddTransient methods in. Net Core dependency Injection,

Source: Internet
Author: User

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);            }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.