我们从代码中可以看到内置依赖注入,它的内置容器是ServiceProvider,我们会把我们的服务注入到ServiceProvider 中来,而IServiceCollection是ServiceProvider的list的集合。
ServiceDescriptor public static IServiceCollection Add(this IServiceCollection collection,IEnumerable<ServiceDescriptor> descriptors) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (descriptors == null) { throw new ArgumentNullException(nameof(descriptors)); } foreach (var descriptor in descriptors) { collection.Add(descriptor); } return collection; }我们可以看到服务注册的时候,提供了ServiceDescriptor
/// <summary> /// Describes a service with its service type, implementation, and lifetime. /// </summary> [DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")] public class ServiceDescriptor {}它是对服务的类型、生命周期、获取服务的方式的描述。
类型 //注册的类型的生命周期 public ServiceLifetime Lifetime { get; } //基类型 public Type ServiceType { get; } //实例类型(派生类型) public Type ImplementationType { get; } //实例对象 public object ImplementationInstance { get; } //注册类型实例化对象的工厂 public Func<IServiceProvider, object> ImplementationFactory { get; }
构造函数
//派生类型 public ServiceDescriptor(Type serviceType,object instance) : this(serviceType, ServiceLifetime.Singleton) { Lifetime = lifetime; ServiceType = serviceType; ImplementationInstance = instance; } //工厂 public ServiceDescriptor(Type serviceType,Func<IServiceProvider, object> factory,ServiceLifetime lifetime) : this(serviceType, lifetime) { Lifetime = lifetime; ServiceType = serviceType; ImplementationFactory = factory; } //具体实例对象 public ServiceDescriptor(Type serviceType,Type implementationType,ServiceLifetime lifetime) : this(serviceType, lifetime) { Lifetime = lifetime; ServiceType = serviceType; ImplementationType = implementationType; } /// <summary> ///获取当前注册类型的实例类型(内部类) /// </summary> /// <returns></returns> internal Type GetImplementationType(){} //真正实例化对象的方法,重载都是调用此类方法 public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime){} public static ServiceDescriptor Singleton(Type serviceType,object implementationInstance){} public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory){} ServiceCollectionServiceExtensions&ServiceCollectionDescriptorExtensions&ServiceCollectionContainerBuilderExtensions这三个方法时ServiceCollection的三个扩展方法分别实现:我们所使用了注册方式;TryAdd和RemoveAll,Replace等操作和构造ServiceProvider实例。
ServiceCollectionServiceExtensions:
代码太多(不同生命周期的注册)就不贴出了,截个图算了。
ServiceCollectionDescriptorExtensions:
![image-20210515122419417](https://gitee.com/wyl1924/cdn/raw/master/img/blog/image-20210515122419417.png public static void TryAdd(this IServiceCollection collection,ServiceDescriptor descriptor) { if (!collection.Any(d => d.ServiceType == descriptor.ServiceType)) collection.Add(descriptor); }
注:Add,RemoveAll,Replace,没什么好说的,其中TryAdd,TryAddEnumerable需要注意到的是:中有服务集合中不存在才会进行过注册。
ServiceCollectionContainerBuilderExtensions