轉載請註明出處: https://home.cnblogs.com/u/zhiyong-ITNote/ 常用擴展方法 註入依賴服務: new ServiceCollection().AddSingleton<IApplicationBuilder, ApplicationBuilder>(); // ...
轉載請註明出處: https://home.cnblogs.com/u/zhiyong-ITNote/
常用擴展方法 註入依賴服務:
new ServiceCollection().AddSingleton<IApplicationBuilder, ApplicationBuilder>();
View Code
// AddSingleton多個重載方法 源碼
public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { if (services == null) { throw new ArgumentNullException(nameof(services)); } return services.AddSingleton(typeof(TService), typeof(TImplementation)); } // Singleton模式 最終的調用 public static IServiceCollection AddSingleton( this IServiceCollection services, Type serviceType, Type implementationType) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } if (implementationType == null) { throw new ArgumentNullException(nameof(implementationType)); } return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } // 所有的Addxxx 最終都是調用Add方法,將ServiceDescriptor添加到IServiceCollection中: private static IServiceCollection Add( IServiceCollection collection, Type serviceType, Type implementationType, ServiceLifetime lifetime) { var descriptor = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(descriptor); return collection; } // IServiceCollection源碼: public interface IServiceCollection : IList<ServiceDescriptor> {}View Code
如上,我們一般在ConfigureService中使用Addxxx將服務註入框架的過程。大概做個總結,其實就是屌用IServiceCollection的Addxxx 擴展方法,隨後調用Add方法,初始化一個ServiceDescriptor,參數是我們註入的介面和類,還有就是生命周期。隨後添加到IServiceCollection中,根據該介面的定義就是一個ServiceDescriptor的集合。
我們看看ServiceProvider的源碼:
public sealed class ServiceProvider : IServiceProvider, IDisposable, IServiceProviderEngineCallback { 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: _engine = new DynamicServiceProviderEngine(serviceDescriptors, callback); break; case ServiceProviderMode.Runtime: _engine = new RuntimeServiceProviderEngine(serviceDescriptors, callback); break; #if IL_EMIT case ServiceProviderMode.ILEmit: _engine = new ILEmitServiceProviderEngine(serviceDescriptors, callback); break; #endif case ServiceProviderMode.Expressions: _engine = new ExpressionsServiceProviderEngine(serviceDescriptors, callback); break; default: throw new NotSupportedException(nameof(options.Mode)); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType"></param> /// <returns></returns> public object GetService(Type serviceType) => _engine.GetService(serviceType); /// <inheritdoc /> public void Dispose() => _engine.Dispose(); void IServiceProviderEngineCallback.OnCreate(IServiceCallSite callSite) { _callSiteValidator.ValidateCallSite(callSite); } void IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) { _callSiteValidator.ValidateResolution(serviceType, scope, _engine.RootScope); } }View Code
該類就是初始化並獲取如下屬性:
/// <inheritdoc /> public ServiceLifetime Lifetime { get; } /// <inheritdoc /> public Type ServiceType { get; } /// <inheritdoc /> public Type ImplementationType { get; } /// <inheritdoc /> public object ImplementationInstance { get; } /// <inheritdoc /> public Func<IServiceProvider, object> ImplementationFactory { get; }View Code
到此,我們的服務註入到asp.net core框架中就完事了,那麼服務的實例化呢?
首先我們理下思路,IServiceProvider介面對應的實現是ServiceProvider,這個類就是實例化了IServiceProvider介面,而IServiceProvider介面只有一個方法:
public object GetService(Type serviceType);
該方法就是獲取註入的服務。但是ServiceProvider類不單單是獲取註入的服務,服務的實例化還是在該類中實現的,我們看下:
public sealed class ServiceProvider : IServiceProvider, IDisposable, IServiceProviderEngineCallback { 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: _engine = new DynamicServiceProviderEngine(serviceDescriptors, callback); break; case ServiceProviderMode.Runtime: _engine = new RuntimeServiceProviderEngine(serviceDescriptors, callback); break; #if IL_EMIT case ServiceProviderMode.ILEmit: _engine = new ILEmitServiceProviderEngine(serviceDescriptors, callback); break; #endif case ServiceProviderMode.Expressions: _engine = new ExpressionsServiceProviderEngine(serviceDescriptors, callback); break; default: throw new NotSupportedException(nameof(options.Mode)); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType"></param> /// <returns></returns> public object GetService(Type serviceType) => _engine.GetService(serviceType); /// <inheritdoc /> public void Dispose() => _engine.Dispose(); void IServiceProviderEngineCallback.OnCreate(IServiceCallSite callSite) { _callSiteValidator.ValidateCallSite(callSite); } void IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) { _callSiteValidator.ValidateResolution(serviceType, scope, _engine.RootScope); } }View Code
可以看到該類的構造函數中就是實例化服務的過程了。很直白的可以看出我們常見的幾種方法來實例化類:反射,Emit,表達式樹等...
目前也算是交代清楚了相關的類。那麼框架具體是如何來實例化的呢?整個的流程是怎麼樣的。篇2再敘
轉載請註明出處: https://home.cnblogs.com/u/zhiyong-ITNote/
源碼地址:https://github.com/aspnet/DependencyInjection