.Net Core依賴註入添加的每個服務,最終都會轉換為一個ServiceDescriptor的實例,ServiceDescriptor包含以下屬性: Lifetime:服務的生命周期(Singleton:單例,Scoped:單個請求期間,Transient:暫時的,每次都創建一個實例) Servi ...
.Net Core依賴註入添加的每個服務,最終都會轉換為一個ServiceDescriptor的實例,ServiceDescriptor包含以下屬性:
Lifetime:服務的生命周期(Singleton:單例,Scoped:單個請求期間,Transient:暫時的,每次都創建一個實例)
ServiceType:服務類型
ImplementationType:服務的實現類型
ImplementationInstance:實現類型的實例
TryAddEnumerable和TryAddTransient都是用於添加服務,他們的卻別就在於過濾條件不同
TryAddEnumerable在添加時會根據服務的ServiceType和ImplementationType進行判斷,如果已存在對應的服務則不添加,適用於為同一個服務添加多個不同的實現的場景,源代碼如下:
if (!services.Any(d =>
d.ServiceType == descriptor.ServiceType &&
d.GetImplementationType() == implementationType))
{
services.Add(descriptor);
}
TryAddTransient在添加時只根據服務的ServiceType進行判斷,如果已存在該類型的服務,則不添加,該方法適用於同一個服務已存在的服務不在添加的場景,源代碼如下:
if (!collection.Any(d => d.ServiceType == descriptor.ServiceType))
{
collection.Add(descriptor);
}