private static void AddSingleService(IServiceCollection services, ServiceDescriptor descriptor, [CanBeNull] DependencyAttribute dependencyAttribute) { if (dependencyAttribute?.ReplaceExisting == true) { services.Replace(descriptor); } else if (dependencyAttribute?.TryAdd == true) { services.TryAdd(descriptor); } else { services.Add(descriptor); } }
/// <summary> /// 将服务实现类型注册到服务集合中 /// </summary> /// <param name="services">服务集合</param> /// <param name="implementationType">要注册的服务实现类型</param> protected virtual void AddToServices(IServiceCollection services, Type implementationType) { if (implementationType.IsAbstract || implementationType.IsInterface) { return; } ServiceLifetime?lifetime = GetLifetimeOrNull(implementationType); if (lifetime == null) { return; } DependencyAttribute dependencyAttribute = implementationType.GetAttribute <DependencyAttribute>(); Type[] serviceTypes = GetImplementedInterfaces(implementationType); //服务数量为0时注册自身 if (serviceTypes.Length == 0) { services.TryAdd(new ServiceDescriptor(implementationType, implementationType, lifetime.Value)); return; } //服务实现显示要求注册身处时,注册自身并且继续注册接口 if (dependencyAttribute?.AddSelf == true) { services.TryAdd(new ServiceDescriptor(implementationType, implementationType, lifetime.Value)); } if (serviceTypes.Length > 1) { List <string> orderTokens = new List <string>() { implementationType.Namespace.Substring("", ".", "") }; orderTokens.AddIfNotExist("OSharp"); serviceTypes = serviceTypes.OrderByPrefixes(m => m.FullName, orderTokens.ToArray()).ToArray(); } //注册服务 for (int i = 0; i < serviceTypes.Length; i++) { Type serviceType = serviceTypes[i]; ServiceDescriptor descriptor = new ServiceDescriptor(serviceType, implementationType, lifetime.Value); if (lifetime.Value == ServiceLifetime.Transient) { services.TryAddEnumerable(descriptor); continue; } bool multiple = serviceType.HasAttribute <MultipleDependencyAttribute>(); if (i == 0) { if (multiple) { services.Add(descriptor); } else { AddSingleService(services, descriptor, dependencyAttribute); } } else { if (multiple) { services.Add(descriptor); } else { //有多个接口,后边的接口注册使用第一个接口的实例,保证同个实现类的多个接口获得同一实例 Type firstServiceType = serviceTypes[0]; descriptor = new ServiceDescriptor(serviceType, provider => provider.GetService(firstServiceType), lifetime.Value); AddSingleService(services, descriptor, dependencyAttribute); } } } }