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

前端 未结 1 2004
鱼传尺愫
鱼传尺愫 2021-01-26 01:07

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

Example: I have an API as below in MyAppService

public class MyAppService : MyAppServiceBase, IM         


        
相关标签:
1条回答
  • 2021-01-26 01:49

    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);
    }
    
    0 讨论(0)
提交回复
热议问题