首先看 ServiceCollection 的定義 //定義 public class ServiceCollection : IServiceCollection { private readonly List<ServiceDescriptor> _descriptors = new List< ...
- 首先看 ServiceCollection 的定義
//定義 public class ServiceCollection : IServiceCollection { private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>(); ...... } //介面定義 public interface IServiceCollection : IList<ServiceDescriptor> { }
由此可見,ServiceCollection 本身是一個 List<ServiceDescriptor> 的集合,下麵我們來看一下 ServiceDescriptor 的定義
public class ServiceDescriptor { //重要的構造函數 public ServiceDescriptor(Type serviceType, Type implementationType, ServiceLifetime lifetime) { } //重要的屬性 /// <summary> /// Service 的生命周期 /// </summary> /// <value></value> public ServiceLifetime Lifetime { get; } /// <summary> /// Service 的類型 /// </summary> /// <value></value> public Type ServiceType { get; } /// <summary> /// Service 的實現類型 /// </summary> /// <value></value> public Type ImplementationType { get; } /// <summary> /// Service 對象 /// </summary> /// <value></value> public object ImplementationInstance { get; } /// <summary> /// 創建 Service 對象的工廠 /// </summary> /// <value></value> public Func<IServiceProvider, object> ImplementationFactory { get; } ...... }
ServiceDescriptor 保存了 Service 類型和 Service 對象之間的關係以及 Service 的生命周期,下麵來看一下 Service 的生命周期
public enum ServiceLifetime { /// <summary> /// 單例 /// </summary> Singleton, /// <summary> /// 範圍內 /// </summary> /// <remarks> /// 在 ASP.NET Core 應用中,每一個請求會創建一個範圍 /// </remarks> Scoped, /// <summary> /// 瞬時 /// </summary> Transient }
再來看一下 IServiceCollection 提供的一些拓展方法
public static class ServiceCollectionServiceExtensions { //基本是3中形式,都是簡單的封裝 public static IServiceCollection AddSingleton(this IServiceCollection services, ...) public static IServiceCollection AddScoped(this IServiceCollection services, ...) public static IServiceCollection AddTransient(this IServiceCollection services, ...) ...... //最終都會調用同一個方法 private static IServiceCollection Add( IServiceCollection collection, Type serviceType, Type implementationType, ServiceLifetime lifetime) { var descriptor = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(descriptor); return collection; } }
這些方法的作用都是為了填充 ServiceCollection 中的 _descriptors 欄位,IServiceCollection 有一個特別重要的方法,BuildServiceProvider,創建 ServiceProvider
public static class ServiceCollectionContainerBuilderExtensions { public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return new ServiceProvider(services, options); } }
- ServiceProvider,Service 的提供者,這是一個非常重要的類,也是容器的核心,主要用來創建 Service 對象的實例
public sealed class ServiceProvider : IServiceProvider, IDisposable{
//ServiceProvider 引擎 private readonly IServiceProviderEngine _engine; //構造函數 internal ServiceProvider(IEnumerable<ServiceDescriptor> serviceDescriptors, ServiceProviderOptions options) { ...... switch (options.Mode) { case ServiceProviderMode.Default:
//.net core 預設是 true if (RuntimeFeature.IsSupported("IsDynamicCodeCompiled")) { _engine = new DynamicServiceProviderEngine(serviceDescriptors, callback); }
else { // Don't try to compile Expressions/IL if they are going to get interpreted _engine = new RuntimeServiceProviderEngine(serviceDescriptors, callback); } break; case ServiceProviderMode.Dynamic: _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); ...... }由此可見,ServiceProvider 創建對象的過程由 ServiceProviderEngine 接管,而 Engine 有4種,分別是 DynamicServiceProviderEngine,RuntimeServiceProviderEngine,ILEmitServiceProviderEngine,ExpressionsServiceProviderEngine,下麵是他們之間的關係,
- 由上圖可知,ServiceProvider 的最終的核心實現應該在 ServiceProviderEngine 這個抽象類中,下麵我們來看一下這個類,我去掉了一些判斷和記錄日誌的邏輯,讓代碼看起來更簡潔
internal abstract class ServiceProviderEngine : IServiceProviderEngine, IServiceScopeFactory { private readonly Func<Type, Func<ServiceProviderEngineScope, object>> _createServiceAccessor; protected ServiceProviderEngine(IEnumerable<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) { _createServiceAccessor = CreateServiceAccessor; Root = new ServiceProviderEngineScope(this); RuntimeResolver = new CallSiteRuntimeResolver(); CallSiteFactory = new CallSiteFactory(serviceDescriptors); CallSiteFactory.Add(typeof(IServiceProvider), new ServiceProviderCallSite()); CallSiteFactory.Add(typeof(IServiceScopeFactory), new ServiceScopeFactoryCallSite()); RealizedServices = new ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object>>(); }
//創建 Service 訪問者 private Func<ServiceProviderEngineScope, object> CreateServiceAccessor(Type serviceType) { var callSite = CallSiteFactory.GetCallSite(serviceType, new CallSiteChain()); if (callSite != null) { //調用子類實現的 獲得 Service 對象的委托來創建對象 return RealizeService(callSite); } return _ => null; }
//調用目標工廠 internal CallSiteFactory CallSiteFactory { get; } //預設運行時解析器 protected CallSiteRuntimeResolver RuntimeResolver { get; } //根容器 public ServiceProviderEngineScope Root { get; } //獲得 Service 對象的委托,由子類實現 protected abstract Func<ServiceProviderEngineScope, object> RealizeService(ServiceCallSite callSite); //獲取 Service 對象 internal object GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) { var realizedService = RealizedServices.GetOrAdd(serviceType, _createServiceAccessor); return realizedService.Invoke(serviceProviderEngineScope); } //創建一個範圍 public IServiceScope CreateScope() { return new ServiceProviderEngineScope(this); } }這個類中有幾個特別重要的對象,
- RuntimeResolver ,Service 對象的創建就是這個對象完成的,當然不同的子類,有不同的實現,
internal class DynamicServiceProviderEngine : CompiledServiceProviderEngine { //該類本身並沒有定義 RutimeResolver 而是通過父類 CompiledServiceProviderEngine 的 ResolverBuilder 實現的 } internal abstract class CompiledServiceProviderEngine : ServiceProviderEngine { //通過編譯條件變數來確定是使用 ILEmit 還是使用 Expression #if IL_EMIT public ILEmitResolverBuilder ResolverBuilder { get; } #else public ExpressionResolverBuilder ResolverBuilder { get; } #endif public CompiledServiceProviderEngine(IEnumerable<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) { #if IL_EMIT ResolverBuilder = new ILEmitResolverBuilder(RuntimeResolver, this, Root); #else ResolverBuilder = new ExpressionResolverBuilder(RuntimeResolver, this, Root); #endif } ...... } internal class RuntimeServiceProviderEngine : ServiceProviderEngine { //該類本身沒有對應的 RuntimeResolver,直接使用父類預設的 CallSiteRuntimeResolver } internal class ILEmitServiceProviderEngine : ServiceProviderEngine { private readonly ILEmitResolverBuilder _expressionResolverBuilder; public ILEmitServiceProviderEngine(IEnumerable<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) { _expressionResolverBuilder = new ILEmitResolverBuilder(RuntimeResolver, this, Root); } ...... } internal class ExpressionsServiceProviderEngine : ServiceProviderEngine { private readonly ExpressionResolverBuilder _expressionResolverBuilder; public ExpressionsServiceProviderEngine(IEnumerable<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) { _expressionResolverBuilder = new ExpressionResolverBuilder(RuntimeResolver, this, Root); } ...... }
所以總結來看,有3個對應的 Resolver 分別是:CallSiteRuntimeResolver,ILEmitResolverBuilder,ExpressionResolverBuilder 這3個類都繼承於 CallSiteVisitor<TArgument, TResult> 的泛型類,只是對應的泛型參數不太一樣
- CallSiteFactory,調用目標工廠,主要用來根據 ServiceDescriptor 的定義創建對應的 ServiceCallSite 對象,然後根據該對象來創建 Service 的實例,這個對象比較複雜,下麵來看一些簡潔的源碼
internal class CallSiteFactory { private const int DefaultSlot = 0; private readonly List<ServiceDescriptor> _descriptors; private readonly Dictionary<Type, ServiceDescriptorCacheItem> _descriptorLookup = new Dictionary<Type, ServiceDescriptorCacheItem>(); public CallSiteFactory(IEnumerable<ServiceDescriptor> descriptors) { _descriptors = descriptors.ToList(); Populate(); } private void Populate() { /* 在實例化 CallSiteFactory 對象時,會將 ServiceDescriptor 對象轉換成字典 Dictionary<Type, ServiceDescriptorCacheItem>, ServiceDescriptorCacheItem 用來將同一個 ServiceType 的 ServiceDescriptor 聚合在一起,其中 ServiceDescriptorCacheItem 的 Last 屬性,是取最後一個 ServiceDescriptor,這也就是為什麼,我們 Add 同一個類型的多個實例時,獲取當前類型的實例時,返回的是最後一個實例的原因 */ foreach (var descriptor in _descriptors) { var cacheKey = descriptor.ServiceType; _descriptorLookup.TryGetValue(cacheKey, out var cacheItem); _descriptorLookup[cacheKey] = cacheItem.Add(descriptor); } } } private struct ServiceDescriptorCacheItem { private List<ServiceDescriptor> _items; public ServiceDescriptor Last { get { return _items[_items.Count - 1]; } } public ServiceDescriptorCacheItem Add(ServiceDescriptor descriptor) { var newCacheItem = new ServiceDescriptorCacheItem(); newCacheItem._item = _item; newCacheItem._items = _items ?? new List<ServiceDescriptor>(); newCacheItem._items.Add(descriptor); return newCacheItem; } }
還有幾個比較關鍵的方法,下麵來看一下代碼
/* 根據 ServiceType 創建 ServiceCallSite, 這個方法類似於一個職責鏈模式, 先嘗試根據普通類型來創建,然後嘗試創建泛型類型,最後嘗試創建可枚舉類型 */ private ServiceCallSite CreateCallSite(Type serviceType, CallSiteChain callSiteChain) { var callSite = TryCreateExact(serviceType, callSiteChain) ?? TryCreateOpenGeneric(serviceType, callSiteChain) ?? TryCreateEnumerable(serviceType, callSiteChain); return callSite; } //嘗試獲取簡單類型對象 private ServiceCallSite TryCreateExact(Type serviceType, CallSiteChain callSiteChain) { if (_descriptorLookup.TryGetValue(serviceType, out var descriptor)) { /* descriptor.Last 這就是為什麼在容器中添加同一個類型的實例多次後,返回的總是最後一個實例 */ return TryCreateExact(descriptor.Last, serviceType, callSiteChain, DefaultSlot); } return null; }
private ServiceCallSite TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, int slot) { if (serviceType == descriptor.ServiceType) { if (descriptor.ImplementationInstance != null) { //Add 時,直接指定實例對象時 callSite = new ConstantCallSite(descriptor.ServiceType, descriptor.ImplementationInstance); } else if (descriptor.ImplementationFactory != null) { //Add 時,指定實例工廠時 callSite = new FactoryCallSite(lifetime, descriptor.ServiceType, descriptor.ImplementationFactory); } else if (descriptor.ImplementationType != null) { //Add 時,指定類型時 callSite = CreateConstructorCallSite(lifetime, descriptor.ServiceType, descriptor.ImplementationType, callSiteChain); } return callSite; } return null; } //嘗試獲取泛型對象 private ServiceCallSite TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, int slot) { if (serviceType.IsConstructedGenericType && serviceType.GetGenericTypeDefinition() == descriptor.ServiceType) { var closedType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments); return CreateConstructorCallSite(lifetime, serviceType, closedType, callSiteChain); } return null; } //嘗試獲取枚舉類型對象 private ServiceCallSite TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain) { if (serviceType.IsConstructedGenericType && serviceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { //獲取泛型的第一個參數 var itemType = serviceType.GenericTypeArguments.Single(); var callSites = new List<ServiceCallSite>(); if (!itemType.IsConstructedGenericType && _descriptorLookup.TryGetValue(itemType, out var descriptors)) { /* 迴圈該 ServiceType 所有的 ServiceDescriptor 這就是為什麼在容器中添加同一個類型的實例多次後,通過 IEnumerable<T> 去獲取時,返回的是多個實例 */ for (int i = 0; i < descriptors.Count; i++) { var descriptor = descriptors[i]; var callSite = TryCreateExact(descriptor, itemType, callSiteChain, slot); callSites.Add(callSite); } } else { //這裡的邏輯代表的是泛型中嵌套泛型的情況,是一個遞歸調用 } return new IEnumerableCallSite(resultCache, itemType, callSites.ToArray()); } return null; } private ServiceCallSite CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain) { //獲取公共的構造函數 var constructors = implementationType.GetTypeInfo() .DeclaredConstructors .Where(constructor => constructor.IsPublic) .ToArray(); ServiceCallSite[] parameterCallSites = null; if (constructors.Length == 0) { //如果沒有獲取到公共的構造函數會拋出異常 throw new InvalidOperationException(Resources.FormatNoConstructorMatch(implementationType)); } else if (constructors.Length == 1) { //當只有一個構造函數時,優化處理邏輯 return new ConstructorCallSite(...); } //存在多個構造函數時,按照構造函數參數的個數倒序排列 Array.Sort(constructors, (a, b) => b.GetParameters().Length.CompareTo(a.GetParameters().Length)); //最優的構造函數 ConstructorInfo bestConstructor = null; //最優構造函數的參數類型 HashSet<Type> bestConstructorParameterTypes = null; for (var i = 0; i < constructors.Length; i++) { var parameters = constructors[i].GetParameters(); var currentParameterCallSites = CreateArgumentCallSites(...); /* 預設參數最多的構造函數為最優的構造函數,但是要根據參數類型在容器中是否存在來判斷, 如果參數多的構造函數,有個別參數在容器中不存在,那麼該構造函數不是最優的 */ if (currentParameterCallSites != null) { if (bestConstructor == null) { bestConstructor = constructors[i]; parameterCallSites = currentParameterCallSites; } else { if (bestConstructorParameterTypes == null) { bestConstructorParameterTypes = new HashSet<Type>(bestConstructor.GetParameters().Select(p => p.ParameterType)); } //如果最優構造函數的參數類型,不是其他構造函數的參數類型的超級,拋出【有歧義】的異常 if (!bestConstructorParameterTypes.IsSupersetOf(parameters.Select(p => p.ParameterType))) { throw new InvalidOperationException(message); } } } } return new ConstructorCallSite(lifetime, serviceType, bestConstructor, parameterCallSites); }
- RuntimeResolver ,Service 對象的創建就是這個對象完成的,當然不同的子類,有不同的實現,
-
由於 ServiceProvider 容器本身只支持構造函數註入,所以我們主要關註每個 Resolver 的 VisitConstructor 方法,
-
CallSiteRuntimeResolver (.net framework 4.6.2 + 預設使用的方式)
internal sealed class CallSiteRuntimeResolver : CallSiteVisitor<RuntimeResolverContext, object> { protected override object VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) { object[] parameterValues; if (constructorCallSite.ParameterCallSites.Length == 0) { parameterValues = Array.Empty<object>(); } else { //迴圈獲取每個參數類型的實例,如果參數類型還依賴於其它的類型,則會遞歸獲取 parameterValues = new object[constructorCallSite.ParameterCallSites.Length]; for (var index = 0; index < parameterValues.Length; index++) { parameterValues[index] = VisitCallSite(constructorCallSite.ParameterCallSites[index], context); } } return constructorCallSite.ConstructorInfo.Invoke(parameterValues); } }
- ILEmitResolverBuilder (.net core 預設使用方式)
/* 由於 IL 我懂的也不是很多,只是大概知道,需要把參數提前準備好放在堆棧上,然後調用 Newobj 就可以實例化對象, 源碼很長,有興趣想要研究的小伙伴,可以自行學習 */ protected override object VisitConstructor(ConstructorCallSite constructorCallSite, ILEmitResolverBuilderContext argument) { foreach (var parameterCallSite in constructorCallSite.ParameterCallSites) { VisitCallSite(parameterCallSite, argument); } argument.Generator.Emit(OpCodes.Newobj, constructorCallSite.ConstructorInfo); return null; } private GeneratedMethod BuildTypeNoCache(ServiceCallSite callSite) { //動態創建方法 var dynamicMethod = new DynamicMethod("ResolveService", attributes : MethodAttributes.Public | MethodAttributes.Static, callingConvention : CallingConventions.Standard, returnType : typeof(object), parameterTypes : new [] { typeof(ILEmitResolverBuilderRuntimeContext), typeof(ServiceProviderEngineScope) }, owner : GetType(), skipVisibility : true); var info = ILEmitCallSiteAnalyzer.Instance.CollectGenerationInfo(callSite); var ilGenerator = dynamicMethod.GetILGenerator(info.Size); //創建方法體 var runtimeContext = GenerateMethodBody(callSite, ilGenerator); return new GeneratedMethod() { Lambda = (Func<ServiceProviderEngineScope, object>) dynamicMethod.CreateDelegate(typeof(Func<ServiceProviderEngineScope, object>), runtimeContext), Context = runtimeContext, DynamicMethod = dynamicMethod }; }
- ExpressionResolverBuilder 可以理解為使用表達式樹將 CallSiteRuntimeResolver 的代碼翻譯了一遍
internal class ExpressionResolverBuilder : CallSiteVisitor<object, Expression> { protected override Expression VisitConstructor(ConstructorCallSite callSite, object context) { var parameters = callSite.ConstructorInfo.GetParameters(); Expression[] parameterExpressions; if (callSite.ParameterCallSites.Length == 0) { parameterExpressions = Array.Empty<Expression>(); } else { //迴圈每一個參數,根據參數創建表達式 parameterExpressions = new Expression[callSite.ParameterCallSites.Length]; for (int i = 0; i < parameterExpressions.Length; i++) { parameterExpressions[i] = Convert(VisitCallSite(callSite.ParameterCallSites[i], context), parameters[i].ParameterType); } } return Expression.New(callSite.ConstructorInfo, parameterExpressions); } }
-
- 總結一下
- ServiceCollection 只不過是用來定義 Service 的類型和定義以及生命周期
- Service 類型的創建是最終是通過不同的 RuntimeResolver 來實現的
- 源碼中還包含大量對緩存的使用,如果沒有緩存,這個容器的效率也就太低了,我在分析源碼的時候直接略過了,原因是,我覺得緩存一定是在先實現後的基礎上再加的,所以我們研究源碼的過程中可以先忽略這些緩存的使用
- 關於 Service 的生命周期我沒有細講,單例和瞬時都非常好理解,其實最複雜的就是 Scope,有點繞的地方在於維護 IDisposable 類型的資源的釋放,當然這個理解起來也不是很難,有興趣的小伙伴可以自行研究
- 源碼分析沒有講最基本的 IOC 概念和容器概念,想要理解這些,前提是要對容器的概念非常瞭解才行