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

相关内容

热门资讯

透视app(WePoKer)w... 透视app(WePoKer)wepoker免费钻石(透视)切实有挂(透明挂教程)1、任何wepoke...
透视科技(WePoKer)we... 透视科技(WePoKer)wepoker透视苹果系统(透视)原来是真的有挂(软件教程);1、用户打开...
透视真的(wepoker)we... 透视真的(wepoker)wepoker有没有插件(透视)都是是真的有挂(安装教程)1、首先打开we...
透视透视(WePoKer)we... 透视透视(WePoKer)wepokerplus作弊(透视)一贯有挂(可靠教程);1、这是跨平台的w...
透视规律(WEPOKER)we... 透视规律(WEPOKER)wepoker黑侠辅助器正版下载(透视)原来真的有挂(透明教程)1、金币登...
透视计算(WePoKer)we... 透视计算(WePoKer)wepoker黑侠辅助器正版下载(透视)本来有挂(黑科技教程);1、许多玩...
透视智能ai(WePoKer)... 透视智能ai(WePoKer)wepoker透视脚本视频(透视)果然存在有挂(2025新版)1、首先...
透视新版(wepoker)we... 透视新版(wepoker)wepoker有没有挂(透视)切实真的有挂(德州教程)一、wepoker有...
透视app(WePoKer)w... 透视app(WePoKer)wepoker挂(透视)都是真的有挂(解说技巧)1、操作简单,无需注册,...
透视规律(wepoker)we... 透视规律(wepoker)wepoker怎么增加运气(透视)确实存在有挂(实用技巧);1、这是跨平台...