.net core 如何利用反射动态批量注入类型

364 阅读1分钟

1 创建attribute类型描述DepandOnAttribute

public class DepandOnAttribute : Attribute
    {
        /// <summary>
        /// 父类型
        /// </summary>
        public Type Type { get; set; }
       
        public DepandOnAttribute(Type t) {
            this.Type = t;
        }
    }

2 在需要自动注入的类型上加上这个描述[DepandOn(typeof(ICourseCategoryService))]

[DepandOn(typeof(ICourseCategoryService))]
 public class CourseCategoryService : ICourseCategoryService
    {
        private CourseCategoryRepository courseCategoryRepository = null;
        private Mapper mapper;
        public CourseCategoryService(CourseCategoryRepository courseCategoryRepository,Mapper mapper) { 
            this.courseCategoryRepository = courseCategoryRepository;
            this.mapper = mapper;
        }

        public List<CategoryItem> GetCategories() {
           ....
        }
    }

3 通过反射批量注入你的类型

 public static void AddIoc(IServiceCollection services) {
            Assembly assembly = Assembly.GetAssembly(typeof(ApplcationExtions));
            Type[] types = assembly.GetTypes();
            foreach (Type type in types) {
                var depandAttribute = type.GetCustomAttribute<DepandOnAttribute>();
                if (type.IsClass
                    && depandAttribute != null) { 
                    services.AddScoped(depandAttribute.Type,type);
                }
            }
        }