ASP .Net Core 获取所有实现接口的类并调用它们的方法
创始人
2024-11-11 13:31:09
0

要获取所有实现接口的类并调用它们的方法,可以使用反射和依赖注入来实现。以下是一个示例代码:

首先,创建一个接口:

public interface IMyInterface
{
    void MyMethod();
}

然后,创建两个实现该接口的类:

public class MyClass1 : IMyInterface
{
    public void MyMethod()
    {
        Console.WriteLine("MyClass1 - MyMethod");
    }
}

public class MyClass2 : IMyInterface
{
    public void MyMethod()
    {
        Console.WriteLine("MyClass2 - MyMethod");
    }
}

接下来,在 ASP .Net Core 的 Startup.cs 文件中注册接口和实现类:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient();
    services.AddTransient();
    //其他配置...
}

最后,在需要获取和调用实现类的地方,使用依赖注入和反射来实现:

public class MyService
{
    private readonly IEnumerable _myInterfaces;

    public MyService(IEnumerable myInterfaces)
    {
        _myInterfaces = myInterfaces;
    }

    public void CallAllMethods()
    {
        foreach (var myInterface in _myInterfaces)
        {
            myInterface.MyMethod();
        }
    }
}

在上述示例中,MyService 类通过构造函数注入了所有实现 IMyInterface 接口的类,并提供了一个 CallAllMethods 方法来循环调用每个实现类的 MyMethod 方法。

通过依赖注入,我们可以在控制器或其他地方直接使用 MyService 类来调用所有实现类的方法:

public class MyController : ControllerBase
{
    private readonly MyService _myService;

    public MyController(MyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        _myService.CallAllMethods();
        return Ok();
    }
}

上述代码示例中,当访问 Index 方法时,将调用 MyService 类的 CallAllMethods 方法,从而调用所有实现类的 MyMethod 方法。

相关内容

热门资讯

每日必看教程!pokermas... 每日必看教程!pokermaster破解版(辅助挂)确实是真的有挂(证实有挂)1、操作简单,无需po...
教学盘点!wepoker怎么看... 教学盘点!wepoker怎么看底牌(辅助挂)原来是有挂(确实有挂)进入游戏-大厅左侧-新手福利-激活...
分享一款!wepoker好友助... 分享一款!wepoker好友助力码(辅助挂)原来是真的有挂(有挂助手)一、wepoker好友助力码可...
科技通报!wepoker透视辅... 科技通报!wepoker透视辅助下载(辅助挂)一贯真的有挂(确实有挂)暗藏猫腻,小编详细说明wepo...
总算了解!pokeplus脚本... 总算了解!pokeplus脚本(辅助挂)确实是真的有挂(有挂细节)1、在pokeplus脚本插件功能...
交流学习经验!wpk软件是正规... 交流学习经验!wpk软件是正规的吗(辅助挂)一贯是有挂(有挂透视)1)wpk软件是正规的吗辅助插件:...
来一盘!hhpoker透视方法... 来一盘!hhpoker透视方法(辅助挂)切实有挂(有挂助手)1、金币登录送、破产送、升级送、活动送。...
推荐一款!wpk透视工作室(辅... 推荐一款!wpk透视工作室(辅助挂)一直是有挂(有挂教学)1、这是跨平台的wpk透视工作室轻量版有透...
分享认知!wepoker有辅助... 分享认知!wepoker有辅助吗(辅助挂)都是存在有挂(有挂分享)1、点击下载安装,wepoker有...
科技介绍!pokerworld... 科技介绍!pokerworld辅助器(辅助挂)本来真的有挂(有挂规律)科技介绍!pokerworld...