private object CreateInstance(Type mappedType, DependencyResolverScope scope) { var constructor = mappedType.GetConstructors(BindingFlags.Public | BindingFlags.Instance); object instance; if (constructor.Length == 0) { instance = Activator.CreateInstance(mappedType); } else { var parameters = constructor[0].GetParameters(); object[] paramInstances = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { paramInstances[i] = GetScopedOrGlobalService(scope, parameters[i].ParameterType); } instance = constructor[0].Invoke(paramInstances); } return(instance); }
private object GetScopedOrGlobalService(DependencyResolverScope scope, Type type) { return(scope != null? scope.GetService(type) : GetService(type)); }
internal object GetService(Type serviceType, DependencyResolverScope scope) { object service = null; Type implementer = null; LifeType?life = null; bool mapped; if (mapped = typeInfoMap.TryGetValue(serviceType, out TypeResolveInfo info) || serviceType.IsGenericType && typeInfoMap.TryGetValue(serviceType.GetGenericTypeDefinition(), out info)) { life = info.LifeType; if (info.Singleton != null) { return(info.Singleton); } if (scope != null && info.LifeType == LifeType.Scope) { service = scope.GetFromCache(serviceType) ?? info.Factory?.CreateInstance((IServiceProvider)scope ?? this, serviceType); } else { service = info.Factory?.CreateInstance((IServiceProvider)scope ?? this, serviceType); } } else { if (!serviceType.IsInterface && !serviceType.IsAbstract) { implementer = serviceType; life = LifeType.Transient; } else { foreach (var resolver in TypeResolvers) { implementer = resolver.ResolveImplementer(serviceType, out life); if (implementer != null) { break; } } } if (implementer != null) { service = CreateInstance(implementer, scope); } } if (service != null && life != null) { switch (life) { case LifeType.Scope: scope?.AddToCache(serviceType, service); break; case LifeType.Singleton: info.Singleton = service; typeInfoMap[serviceType] = info; break; default: break; } } return(service); }