net5学习笔记---依赖注入 (2)

我们从代码中可以看到内置依赖注入,它的内置容器是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 {}

它是对服务的类型、生命周期、获取服务的方式的描述。

image-20210515103733823


类型

//注册的类型的生命周期 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:
代码太多(不同生命周期的注册)就不贴出了,截个图算了。

image-20210515121957047


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

public static class ServiceCollectionContainerBuilderExtensions { public static ServiceProvider BuildServiceProvider(this IServiceCollection services) public static ServiceProvider BuildServiceProvider(this IServiceCollection services, bool validateScopes) public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) } IServiceProvider public sealed class ServiceProvider : IServiceProvider, IDisposable, IServiceProviderEngineCallback { // ServiceProvider的扩展接口 // 使用这个接口的子类进行调用缓存各种注册服务和调用访问者对象进行获取实例对象 private readonly IServiceProviderEngine _engine; /// 缓存类型(访问者模式) private readonly CallSiteValidator _callSiteValidator; internal ServiceProvider(IEnumerable<ServiceDescriptor> serviceDescriptors, ServiceProviderOptions options) { IServiceProviderEngineCallback callback = null; if (options.ValidateScopes) { callback = this; _callSiteValidator = new CallSiteValidator(); } //实例化工作引擎类型 switch (options.Mode) { case ServiceProviderMode.Dynamic: // 实例化 DynamicServiceProviderEngine _engine = new DynamicServiceProviderEngine(serviceDescriptors, callback); break; case ServiceProviderMode.Runtime: _engine = new RuntimeServiceProviderEngine(serviceDescriptors, callback); break; case ServiceProviderMode.ILEmit: _engine = new ILEmitServiceProviderEngine(serviceDescriptors, callback); break; case ServiceProviderMode.Expressions: _engine = new ExpressionsServiceProviderEngine(serviceDescriptors, callback); break; default: throw new NotSupportedException(nameof(options.Mode)); } } // 获取指定类型的服务对象 public object GetService(Type serviceType) => _engine.GetService(serviceType); public void Dispose() => _engine.Dispose(); //创建服务实例缓存 void IServiceProviderEngineCallback.OnCreate(ServiceCallSite callSite) =>_callSiteValidator.ValidateCallSite(callSite); //服务实例的校验 void IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) =>_callSiteValidator.ValidateResolution(serviceType, scope, _engine.RootScope); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzwxsy.html