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();
        }
相关推荐
CreasyChan19 小时前
unity 对象池实测可用
unity·c#
一个帅气昵称啊19 小时前
AI搜索增强C#实现多平台联网搜索并且将HTML内容转换为结构化的Markdown格式并整合内容输出结果
人工智能·c#·html
源代码•宸19 小时前
Leetcode—146. LRU 缓存【中等】(哈希表+双向链表)
后端·算法·leetcode·缓存·面试·golang·lru
云草桑19 小时前
在C# .net中RabbitMQ的核心类型和属性,除了交换机,队列关键的类型 / 属性,影响其行为
c#·rabbitmq·.net·队列
guygg8819 小时前
C#实现的TCP/UDP网络调试助手
网络·tcp/ip·c#
2501_940198691 天前
从“数据孤岛”到“智慧医脑”:实战 MCP 协议安全接入 HIS 系统,构建医疗级 AI 辅助诊断合规中台
人工智能·安全·asp.net
1314lay_10071 天前
C# 点击一次api,限流中间件但是X-Rate-Limit-Remaining剩余数量减少2
visualstudio·c#
“抚琴”的人1 天前
C#上位机工厂模式
开发语言·c#
小马爱打代码1 天前
SpringBoot:封装 starter
java·spring boot·后端
STARSpace88881 天前
SpringBoot 整合个推推送
java·spring boot·后端·消息推送·个推