public static void AddTransient <T1, T2>(this IMyServiceCollection services) where T2 : T1 { serviceTypes.Add(typeof(T1), MyServiceDescriptor.Transient(typeof(T2))); }
private static MyServiceDescriptor GetServiceDescriptor(Type serviceType) { MyServiceDescriptor serviceDescriptor = null; if (scopedServiceTypes == null) { scopedServiceTypes = new Dictionary <Type, MyServiceDescriptor>(); } else if (scopedServiceTypes.TryGetValue(serviceType, out serviceDescriptor)) { return(serviceDescriptor); } if (!serviceTypes.TryGetValue(serviceType, out serviceDescriptor)) { serviceDescriptor = MyServiceDescriptor.Transient(serviceType); } else if (serviceDescriptor.Scope == MyServiceScope.Singleton) { var hasInstance = serviceDescriptor.Instance != null; if (hasInstance) { return(serviceDescriptor); } serviceDescriptor.slim.EnterReadLock(); hasInstance = serviceDescriptor.Instance != null; serviceDescriptor.slim.ExitReadLock(); if (hasInstance) { return(serviceDescriptor); } } if (serviceDescriptor.Type.IsInterface) { throw new NotImplementedException(); } var constructor = serviceDescriptor.Type .GetConstructors(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(); var parameters = new ArrayList(); foreach (var parameter in constructor.GetParameters()) { var descriptor = GetServiceDescriptor(parameter.ParameterType); // 单例不能访问Scoped的实例 if (serviceDescriptor.Scope == MyServiceScope.Singleton) { if (descriptor.Scope == MyServiceScope.Scoped) { throw new Exception("Scoped"); } } parameters.Add(parameter.HasDefaultValue ? parameter.DefaultValue : descriptor.Instance); } var instance = Activator.CreateInstance(serviceDescriptor.Type, parameters.ToArray()); if (serviceDescriptor.Scope == MyServiceScope.Scoped) { scopedServiceTypes.Add(serviceType, serviceDescriptor = MyServiceDescriptor.Scoped(instance)); } else if (serviceDescriptor.Scope == MyServiceScope.Singleton) { serviceDescriptor.slim.EnterWriteLock(); serviceDescriptor.Instance = instance; serviceDescriptor.slim.ExitWriteLock(); } else { serviceDescriptor = MyServiceDescriptor.Transient(instance); } return(serviceDescriptor); }
public static void AddTransient <T1>(this IMyServiceCollection services) { serviceTypes.Add(typeof(T1), MyServiceDescriptor.Transient(typeof(T1))); }