Ejemplo n.º 1
0
        /// <summary>
        /// 用DI批量注入批定接口类型的实现类程序集中的实现类
        /// </summary>
        /// <param name="service">服务收藏</param>
        /// <param name="interfaceType">接口类型</param>
        /// <param name="lifecycle">生命周期,默认为瞬时</param>
        /// <param name="implClassAssemblys">接口程序集的名称(不包含文件扩展名)</param>
        /// <returns>服务收藏</returns>
        public static IServiceCollection RegisterAssemblyWithInterfaceMapImpls(this IServiceCollection service, Type interfaceType,
                                                                               ServiceLifetime lifecycle = ServiceLifetime.Transient, params string[] implClassAssemblys)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (implClassAssemblys.IsNullOrLength0())
            {
                throw new ArgumentNullException(nameof(implClassAssemblys));
            }

            Assembly[] assemblies = new Assembly[implClassAssemblys.Length];
            for (var i = 0; i < implClassAssemblys.Length; i++)
            {
                assemblies[i] = Assembly.Load(implClassAssemblys[i]);
            }

            var implTypes = ReflectExtensions.GetImplClassType(assemblies, interfaceType);

            if (implTypes.IsNullOrLength0())
            {
                return(service);
            }

            foreach (var it in implTypes)
            {
                if (it.IsAbstract)
                {
                    continue;
                }

                switch (lifecycle)
                {
                case ServiceLifetime.Transient:
                    service.AddTransient(interfaceType, it);

                    break;

                case ServiceLifetime.Scoped:
                    service.AddScoped(interfaceType, it);

                    break;

                case ServiceLifetime.Singleton:
                    service.AddSingleton(interfaceType, it);

                    break;

                default:
                    throw new NotSupportedException($"不支持的生命周期:{lifecycle}");
                }
            }

            return(service);
        }
        /// <summary>
        /// 自动找出实现IAutoMapperConfig接口的配置
        /// </summary>
        /// <param name="assemblies">程序集数组</param>
        public static void AutoRegisterConfig(Assembly[] assemblies)
        {
            var types = ReflectExtensions.GetImplClassType(assemblies, typeof(IAutoMapperConfig));

            if (types.IsNullOrLength0())
            {
                return;
            }

            foreach (var t in types)
            {
                var config = t.Assembly.CreateInstance(t.FullName) as IAutoMapperConfig;
                mapperConfigs.Add(config);
            }
        }