根据NETCore的注入方式添加三个接口
/// <summary> /// 瞬时注入服务接口 /// </summary> public interface ITransient { } /// <summary> /// 作用域注入服务接口 /// </summary> public interface IScoped { } /// <summary> /// 单例注入服务接口 /// </summary> public interface ISingleton { }
自动注入的核心代码
/// <summary> /// 自动注入的扩展方法 /// </summary> public static class AutoRegisterHelper { /// <summary> /// 自动注入的扩展方法 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection CustAutoRegister(this IServiceCollection services) { // 需要自动注入的程序集名称 var registerDllNameList = new List<string> { "BLL","DAL" }; var assemblyList = new List<Assembly>(); foreach (var itemName in registerDllNameList) assemblyList.Add(Assembly.Load(itemName)); var types = assemblyList.SelectMany(x => x.GetTypes())//获取所有类 .Distinct()//排重 .Where(x => x.IsClass && !x.IsAbstract)//排除无效数据 .ToList(); // 分别注册三种生命周期 Register<ITransient>(types, services.AddTransient, services.AddTransient); Register<IScoped>(types, services.AddScoped, services.AddScoped); Register<ISingleton>(types, services.AddSingleton, services.AddSingleton); return services; } /// <summary> /// 根据服务标记的生命周期interface,不同生命周期注册到容器里面 /// </summary> /// <typeparam name="TLifetime">注册的生命周期</typeparam> /// <param name="types">集合类型</param> /// <param name="register">委托:成对注册</param> /// <param name="registerDirectly">委托:直接注册服务实现</param> private static void Register<TLifetime>(IEnumerable<Type> types, Func<Type, Type, IServiceCollection> register, Func<Type, IServiceCollection> registerDirectly) { //找到所有标记了Tlifetime生命周期接口的实现类 var tImplements = types.Where(x => x.GetInterfaces().Any(tinterface => tinterface == typeof(TLifetime))).ToList(); //遍历,挨个以其他所有接口为key,当前实现为value注册到容器中 foreach (var t in tImplements) { //获取除生命周期接口外的所有其他接口 var interfaces = t.GetInterfaces().Where(x => x != typeof(TLifetime)); if (interfaces.Any()) { foreach (var i in interfaces) { register(i, t); } } // 有时需要直接注入实现类本身 //registerDirectly(t); } } }
标签:接口,services,var,NET6,public,types,注入 From: https://www.cnblogs.com/CRobot/p/18298612