private static bool ShouldExclude(Type type, IocScannerOptions options) { if (options.Excludes != null) { foreach (var func in options.Excludes) { if (func.Invoke(type)) { return(true); } } } return(false); }
/// <summary> /// Scan supplied assemblies and bind them automatically to service collection based on attribute and convention /// </summary> /// <param name="source"></param> /// <param name="assemblies"></param> public static IServiceCollection Scan(this IServiceCollection source, IEnumerable <Assembly> assemblies, IocScannerOptions options) { options = options ?? new IocScannerOptions(); var skipAutoBindAttributeFullName = typeof(SkipAutoBindAttribute).FullName; var autoBindAttributeFullName = typeof(AutoBindAttribute).FullName; if (options.TypesToExclude?.Any() ?? false) { options.Exclude(t => options.TypesToExclude.Any(e => e.FullName == t.FullName)); } foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { var typeInfo = type.GetTypeInfo(); var isAbstract = typeInfo.IsAbstract || typeInfo.IsInterface; if (isAbstract) { continue; } var attributes = typeInfo.GetCustomAttributes(); if (attributes.Any(a => a.GetType().FullName == skipAutoBindAttributeFullName)) { continue; } if (ShouldExclude(type, options)) { continue; } var autoBindAttribute = attributes.FirstOrDefault(x => x.GetType().FullName == autoBindAttributeFullName) as AutoBindAttribute; if (autoBindAttribute == null && options.SkipWhenAutoBindMissing) { continue; } var interfaces = typeInfo.GetInterfaces(); if (!interfaces.Any()) { if (autoBindAttribute != null) { BindToSelf(source, type, autoBindAttribute); } continue; } if (interfaces.Any(x => x == typeof(IServiceRegistry))) { var registry = Activator.CreateInstance(type) as IServiceRegistry; registry.Register(source); continue; } if (autoBindAttribute == null) { autoBindAttribute = new AutoBindAttribute(LifeCycle.Transient) { UseTryAdd = false }; } BindToIntefaces(source, type, interfaces, autoBindAttribute); } } return(source); }
/// <summary> /// Scane calling assembly and bind all classes in that assembly automatically to service collection based on attribute and convention /// </summary> /// <param name="source"></param> /// <param name="options"></param> public static IServiceCollection Scan <T>(this IServiceCollection source, IocScannerOptions options) { return(Scan(source, new[] { typeof(T).GetTypeInfo().Assembly }, options)); }