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();
        }
相关推荐
Larcher1 小时前
React Router 不只是页面跳转:从 SPA 路由到权限守卫的完整实践
javascript·后端
Larcher1 小时前
大模型为什么每次回答都不一样?一文搞懂 Temperature、Top K 与 Top P
javascript·后端
LucianaiB3 小时前
毕业老学长给我留的最后一句话是:“AI 写的,别挂我名。” 我直接 神(Seed Evolving) 来!助我!
后端
IvanCodes3 小时前
RAG 实战教程(一):RAG 工作原理与完整流程——分片、索引、召回、重排和生成
人工智能·后端·agent
CodeSheep4 小时前
稚晖君公司人事大变动,来了!
前端·后端·程序员
小满zs4 小时前
Go语言第八章(函数)
后端·go
stark张宇6 小时前
实战Go高级特性:Context超时控制、defer资源回收与Channel通信的关键避坑点
后端·go
hez20106 小时前
.NET 11 Runtime Async 详解
c#·.net·.net core
凤山老林7 小时前
Spring Boot @Async 线上实战:从默认配置到生产级线程池治理
java·spring boot·后端
猿长大人8 小时前
C# | Serilog 新手入门
开发语言·c#·.net·log