/// <summary> /// Adds all classes and factory methods, from namespaces that start with <paramref name="namespace"/>, with <see cref="RegisterScoped"/>, /// <see cref="RegisterSingleton"/> or <see cref="RegisterTransient"/> attribute for classes /// and <see cref="RegisterScopedFactory"/>, <see cref="RegisterSingletonFactory"/> or <see cref="RegisterTransientFactory"/> for /// factory methods to <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">Service collection.</param> /// <param name="namespace">Scanned namespace.</param> /// <returns></returns> public static IServiceCollection AutoRegister(this IServiceCollection services, string @namespace) { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); services.AddFactories(DependifyUtils.GetFactoryMethodsFromNamespace(assemblies, @namespace)); services.AddClasses(DependifyUtils.GetClassTypesFromNamespace(assemblies, @namespace)); return(services); }
private static IServiceCollection AddFactoryMethods(this IServiceCollection services, ServiceLifetime factoryLifetime, Type factoryReturnType, MethodInfo methodInfo) { switch (factoryLifetime) { case ServiceLifetime.Singleton: return(services.AddSingleton(factoryReturnType, DependifyUtils.GetFactoryMethod(methodInfo))); case ServiceLifetime.Scoped: return(services.AddScoped(factoryReturnType, DependifyUtils.GetFactoryMethod(methodInfo))); case ServiceLifetime.Transient: return(services.AddTransient(factoryReturnType, DependifyUtils.GetFactoryMethod(methodInfo))); default: throw new ArgumentOutOfRangeException($"{factoryLifetime} is not supported."); } }
/// <summary> /// Adds all classes and factory methods from specified <paramref name="assemblies"/> with <see cref="RegisterScoped"/>, /// <see cref="RegisterSingleton"/> or <see cref="RegisterTransient"/> attribute for classes /// and <see cref="RegisterScopedFactory"/>, <see cref="RegisterSingletonFactory"/> or <see cref="RegisterTransientFactory"/> for /// factory methods to <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">Service collection.</param> /// <param name="assemblies">Assemblies to scan</param> /// <returns>Service collection.</returns> public static IServiceCollection AutoRegister(this IServiceCollection services, params Assembly[] assemblies) { services.AddFactories(DependifyUtils.GetFactoryMethods(assemblies)); services.AddClasses(DependifyUtils.GetClassTypes(assemblies)); return(services); }