/// <summary> /// /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="services"></param> /// <param name="lifeTime"></param> /// <param name="namespaceStr">namespace search with startwith option</param> private static void BindType <TInterface>(IServiceCollection services, ServiceLifetime lifeTime = ServiceLifetime.Scoped, string namespaceStr = null) { IEnumerable <TypeMap> maps = TypeMapHelper.GetTypeMaps <TInterface>(AppDomain.CurrentDomain.GetAssemblies(), namespaceStr); foreach (var typeMap in maps) { foreach (var serviceType in typeMap.ServiceTypes) { var implementationType = typeMap.ImplementationType; if (!implementationType.IsAssignableTo(serviceType)) { throw new InvalidOperationException($@"Type ""{implementationType.ToFriendlyName()}"" is not assignable to ""${serviceType.ToFriendlyName()}""."); } var descriptor = new ServiceDescriptor(serviceType, implementationType, lifeTime); var oldDescription = services.FirstOrDefault(t => t.ServiceType == typeof(TInterface)); if (oldDescription != null) { services.Remove(oldDescription); } var oldDescriptionImp = services.FirstOrDefault(t => t.ServiceType == implementationType); if (oldDescriptionImp != null) { services.Remove(oldDescriptionImp); } services.Add(descriptor); } } }
private static void BindType <TInterface, TProxySelector>(IServiceCollection services, string namespaceStr = null) where TProxySelector : class, IProxySelector, new() { using (TProxySelector proxySelector = new TProxySelector()) { ServiceLifetime lifetime = ServiceLifetime.Scoped; if (typeof(TInterface) == typeof(ISingletonType)) { lifetime = ServiceLifetime.Singleton; } else if (typeof(TInterface) == typeof(ITransientType)) { lifetime = ServiceLifetime.Transient; } IEnumerable <TypeMap> maps = TypeMapHelper.GetTypeMaps <TInterface>(AppDomain.CurrentDomain.GetAssemblies(), namespaceStr); foreach (var typeMap in maps) { var implementationType = typeMap.ImplementationType; var types = typeMap.ServiceTypes.Where(t => t != typeof(IProxySelector) && t != typeof(IInterceptorContext) && t != typeof(IProxyGenerator) && t != typeof(ISingletonType) && t != typeof(IScopedType) && t != typeof(ITransientType)).ToList(); types.Add(typeMap.ImplementationType); var oldDescriptionImp = services.FirstOrDefault(t => t.ServiceType == implementationType); if (oldDescriptionImp != null) { services.Remove(oldDescriptionImp); } bool isIncludeAspect = proxySelector.ShouldInterceptTypes(types); if (isIncludeAspect) { BindInterceptorTypeMap <TInterface>(services, typeMap, lifetime); } else { BindTypeMap <TInterface>(services, typeMap, lifetime); } } } }