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();
        }
相关推荐
用户084465256374 分钟前
Docker 部署 MongoDB Atlas 到服务端
后端
Yorlen_Zhang22 分钟前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝19135 分钟前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
Anita_Sun42 分钟前
一看就懂的 Haskell 教程 - 类型推断机制
后端·haskell
大鹏说大话1 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
Anita_Sun1 小时前
一看就懂的 Haskell 教程 - 类型签名
后端·haskell
七八星天1 小时前
C#代码设计与设计模式
后端
砍材农夫1 小时前
threadlocal
后端
神奇小汤圆2 小时前
告别手写HTTP请求!Spring Feign 调用原理深度拆解:从源码到实战,一篇搞懂
后端
布列瑟农的星空2 小时前
前端都能看懂的Rust入门教程(三)——控制流语句
前端·后端·rust