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

相关内容

热门资讯

黑科技科技(wepoke智能a... 黑科技科技(wepoke智能ai)wepower使用说明书(wepOkE)素来是真的有挂(确实有挂)...
黑科技模拟器(wepoke智能... WePoker透视辅助工具核心要点解析‌,黑科技模拟器(wepoke智能ai)wepoke是机器发牌...
黑科技脚本(wepokeai代... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏中打牌都...
黑科技辅助挂(wepoke真的... 黑科技辅助挂(wepoke真的有挂)wepoke 软件(wEPOKE)固有真的有挂(有挂猫腻)-哔哩...
黑科技辅助挂(wepoke黑科... 黑科技辅助挂(wepoke黑科技)wepoke软件透明挂演示(wEpOke)一直真的有挂(真的有挂)...
黑科技app(wepoke真的... 此外,数据分析德州()辅助神器app还具备辅助透视行为开挂功能,通过对客户透明挂的深入研究,你可以了...
黑科技智能ai(wepoke辅... 黑科技智能ai(wepoke辅助插件)wepoke软件透明(WEPOke)先前是有挂(果真有挂)-哔...
黑科技模拟器(wepoke透明... 黑科技模拟器(wepoke透明黑科技)wepoke德州扑克用ai代打(WEPOKE)最初存在有挂(有...
黑科技插件(wepoke辅助插... 黑科技插件(wepoke辅助插件)wepoke软件透明(WEPOke)从来是真的有挂(有挂解惑)-哔...
黑科技美元局(wepoke智能... 黑科技美元局(wepoke智能ai)wepoke辅助真的假的(wepoKE)原先真的有挂(竟然有挂)...