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 方法。

相关内容

热门资讯

透视脚本"hhpok... 这是一款非常优秀的hhpoker是真的还是假的 ia辅助检测软件,能够让你了解到hhpoker是真的...
透视规律"wepok... 透视规律"wepoker怎么破解游戏"详细辅助可靠技巧(黑侠破解教程);《WPK辅助透视》‌:支持手...
透视透视挂"wepo... 透视透视挂"wepoker俱乐部辅助"详细辅助2025新版教程(开脚本视频辅助);1分钟了解详细教程...
透视玄学"大菠萝免费... 透视玄学"大菠萝免费辅助"详细辅助曝光教程(的辅助器软件)这是由厦门游乐互动科技有限公司精心打造的一...
透视美元局"德普辅助... 透视美元局"德普辅助软件"详细辅助必备教程(辅助器下载软件);原来确实真的有挂(需添加指定薇1367...
透视科技"wejok... 透视科技"wejoker辅助器怎么卖"详细辅助wepoke教程(底牌透视透视);原来确实真的有挂(需...
透视辅助"pokem... 透视辅助"pokemmo手机版修改器"详细辅助实用技巧(私人局俱乐部辅助教程)是一款可以让一直输的玩...
透视好牌"hhpok... 透视好牌"hhpoker脚本"详细辅助安装教程(辅助器是真的技巧)准备好在hhpoker脚本 ia的...
透视肯定"uupok... 这是一款非常优秀的uupoker有透视吗 ia辅助检测软件,能够让你了解到uupoker有透视吗中牌...
透视ai"wepok... 1、透视ai"wepoker有辅助器吗"详细辅助2025新版总结(网页版透视方法透明)2、进入游戏-...