asp.net core6 webapi 使用反射批量注入接口层和实现接口层的接口的类到ioc中

IBLL接口层类库

csharp 复制代码
namespace IBLL
{
    public interface ICar
    {
        string CarName();
    }
}
namespace IBLL
{
    public interface IRed
    {
        string RedName();
    }
}

BLL实现接口层类库

csharp 复制代码
namespace BLL
{
    public class Car : ICar
    {
        public string CarName()
        {
            return "BBA";
        }
    }
}
namespace BLL
{
    public class Red : IRed
    {
        public string RedName()
        {
            return "红色";
        }
    }
}

program中利用反射批量注入

csharp 复制代码
 // 获取实现接口的类库的程序集
            var assembly = Assembly.Load("BLL");
            //获取定义接口的类库的程序集
            var assembly1 = Assembly.Load("IBLL");
            // 获取所有接口类型
            var interfaceTypes = assembly1.GetTypes().Where(t => t.IsInterface).ToList();

            // 遍历接口类型
            foreach (var interfaceType in interfaceTypes)
            {
                // 获取实现该接口的所有类型
                var implementationTypes = assembly.GetTypes().Where(t => interfaceType.IsAssignableFrom(t) && !t.IsAbstract).ToList();

                // 注册实现类型到IoC容器中
                foreach (var implementationType in implementationTypes)
                {
                    builder.Services.AddTransient(interfaceType, implementationType);
                }
            }

在控制器中使用构造函数传参就可以调用已经注册的所有是是实现接口的类了的实列了

csharp 复制代码
public readonly ICar _car;
        public readonly IRed _red;

        public WeatherForecastController(IRed red, ICar car)
        {
            _red = red;
            _car = car;
        }
        [HttpGet]
        public string car()
        {
            return _car.CarName();
        }

        [HttpGet]
        public string red()
        {
            return _red.RedName();
        }
相关推荐
步步为营DotNet3 小时前
借助 Microsoft.Extensions.AI 与 ASP.NET Core 10 实现智能 Web 应用故障预测
人工智能·microsoft·asp.net
mCell4 小时前
你以为短链接只是 Hash + 301/302?
后端·算法·架构
咖啡八杯4 小时前
GoF设计模式——迭代器模式
java·后端·设计模式·迭代器模式
贾斯汀frank7 小时前
C# 15 类型系统改进:Union Types
开发语言·windows·c#
IT_陈寒8 小时前
SpringBoot自动配置不是你以为的那样的智能
前端·人工智能·后端
时代的狂8 小时前
如何理解 C# 的 async 和 await
c#·.netcore·async·await
程序员张310 小时前
SpringBoot集成BCrypt密码加密库
java·spring boot·后端
CaffeinePro10 小时前
FastAPI数据库集成SQLAlchemy异步ORM全方案
后端·fastapi
小旭Coding10 小时前
凌晨告警轰炸!Go 服务协程只增不减,内存持续暴涨直至 OOM
后端
半个落月10 小时前
用 LangChain.js 手写一个能读写文件和执行命令的 Mini Cursor
javascript·人工智能·后端