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

相关内容

热门资讯

透视资料!WePoKer辅助器... 透视资料!WePoKer辅助器(透视)其实有辅助神器(哔哩哔哩)1、全新机制【WePoKer辅助器a...
透视妙招!aapoker辅助软... 透视妙招!aapoker辅助软件合法吗(透视)都是真的是有辅助辅助器(哔哩哔哩)1、aapoker辅...
透视要领!wepoker挂(透... 透视要领!wepoker挂(透视)都是是有辅助下载(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活...
透视经验!wepoker透视是... 透视经验!wepoker透视是真的吗(透视)果然真的有辅助神器(哔哩哔哩)wepoker透视是真的吗...
透视秘籍!wepoker透视脚... 透视秘籍!wepoker透视脚本免费app(透视)一直存在有辅助工具(哔哩哔哩)1、超多福利:超高返...
透视模块!德州之星扫描器(透视... 透视模块!德州之星扫描器(透视)都是有辅助辅助器(哔哩哔哩)运德州之星扫描器辅助工具,进入游戏界面。...
透视步骤!wepoker怎么获... 透视步骤!wepoker怎么获得好牌(透视)都是存在有辅助软件(哔哩哔哩)1、金币登录送、破产送、升...
透视法门!福建大菠萝万能辅助器... 透视法门!福建大菠萝万能辅助器(透视)都是是真的辅助软件(哔哩哔哩)1、透视法门!福建大菠萝万能辅助...
透视要领!pokeplus脚本... 透视要领!pokeplus脚本(透视)本来有辅助安装(哔哩哔哩)1、pokeplus脚本透视辅助软件...
透视项目!wepoker游戏下... 透视项目!wepoker游戏下载(透视)其实是有辅助神器(哔哩哔哩)1、超多福利:超高返利,海量正版...