如何使用反射通过字符串名称调用API? [英] How to use reflection to call a API by string name?

查看:57
本文介绍了如何使用反射通过字符串名称调用API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过字符串名称在另一个AppService中调用API?

How to call an API in another AppService by string name?

示例:我在MyAppService中具有如下所示的API

Example: I have an API as below in MyAppService

public class MyAppService : MyAppServiceBase, IMyAppService
    {
        private readonly IRepository<MyEntity> _myEntityRepository;    
        public CommonLookupAppService(IRepository<MyEntity> myEntityRepository)
            {
                 _myEntityRepository = myEntityRepository;            
            }

        public async Task<MyOutput> MyMethod (MyInput input)
            {

            }
    }

如何将MyMethod作为字符串保存到数据库中并在另一个应用程序服务中调用它?我有很多这样的方法,所以我不想使用switch case来调用它们.我想将此方法程序集名称作为字符串保存到数据库中,并在需要时调用它.我该怎么办?

How to save MyMethod as a string into the database and invoke it in another app service? I have many methods like this so I don't want to use switch case to call them. I want to save this method assembly name to the database as a string and invoke it when needed. What should I do?

推荐答案

您可以使用以下组合:

  • Type.GetType(string)
  • Type.GetMethod(string)
  • IIocResolver.ResolveAsDisposable(Type) —通过ABP
  • MethodInfo.Invoke(Object, Object[])
  • Type.GetType(string)
  • Type.GetMethod(string)
  • IIocResolver.ResolveAsDisposable(Type) — by ABP
  • MethodInfo.Invoke(Object, Object[])
// var appServiceName = "MyAppService";
// var methodName = "MyMethod";
// var input = new object[] { new MyInput() };

var appServiceType = Type.GetType(appServiceName);
var method = appServiceType.GetMethod(methodName);

using (var appService = IocResolver.ResolveAsDisposable(appServiceType))
{
    var output = await (Task)method.Invoke(appService.Object, input);
}

这篇关于如何使用反射通过字符串名称调用API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆