当前位置: 移动技术网 > IT编程>开发语言>.net > .Net Core依赖注入中TryAddEnumerable 和TryAddTransient方法的区别

.Net Core依赖注入中TryAddEnumerable 和TryAddTransient方法的区别

2018年03月13日  | 移动技术网IT编程  | 我要评论

半熟 林染,官道无疆txt,骚mm

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网