How to use reflection to call a API by string name?

橙三吉。 提交于 2019-12-02 16:31:41

问题


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

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)
            {

            }
    }

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?


回答1:


You can use a combination of:

  • 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);
}


来源:https://stackoverflow.com/questions/47091480/how-to-use-reflection-to-call-a-api-by-string-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!