DOTNET CORE源码分析之ServiceDescriptor

  ServiceDescriptor在.net core中的作用就是DI中注入服务元素的描述。每一个元素核心内容部分包括需要注入的服务元素的类型ServiceType,它对应的接口(如果有的话)ImplementationType,以及服务元素的生命周期ServiceLifetime。

  源码中ServiceDescriptor是一个普通类,一共有4个构造函数,分别是如下:

public ServiceDescriptor(Type serviceType, Type implementationType, ServiceLifetime lifetime): this(serviceType, lifetime)

需要带入服务元素的类型,服务元素对应接口的类型,服务元素的生命周期。

public ServiceDescriptor(Type serviceType, object instance): this(serviceType, ServiceLifetime.Singleton)

需要带入服务元素的类型,服务元素实例,默认是单例的。

public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime): this(serviceType, lifetime)

需要带入服务元素的类型,服务工厂(用于生成服务实例),服务元素的生命周期。  

private ServiceDescriptor(Type serviceType, ServiceLifetime lifetime)

需要带入服务元素的类型,服务元素的生命周期,这个是最基本的构造函数,但是没有赋予实例对象,所以不公开,不然就不知道这个服务的真实值是什么了,也就没有注入的意义了。

  ServiceDescriptor中有几个很重要的函数,下面我简单介绍一下:

  第一个:Describe函数,用于生成ServiceDescriptor类,一共有3个重载,分别是如下:

public static ServiceDescriptor Describe(Type serviceType,Func<IServiceProvider, object> implementationFactory,ServiceLifetime lifetime)

public static ServiceDescriptor Describe(Type serviceType,Type implementationType,ServiceLifetime lifetime)

private static ServiceDescriptor Describe<TService, TImplementation>(ServiceLifetime lifetime)

public static ServiceDescriptor Singleton(Type serviceType,object implementationInstance)

它们分别对应上面的构造函数,也就是说为实例化ServiceDescriptor提供另外一种方式

  第二个:Singleton函数,用于生成单例化的ServiceDescriptor类,重载方式不另外说明。

  第三个:Scoped函数,用于生成服务范围内的ServiceDescriptor类,重载方式不另外说明。

  第四个:Transient函数,用于生成每次不同的ServiceDescriptor类,重载方式不另外说明。

  另外,ServiceLifetime 是一个枚举类型,枚举内容有Singleton,Scoped,Transient。

  

原文地址:https://www.cnblogs.com/lizhizhang/p/12541524.html