Search code examples
reflectionaspnetboilerplate

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


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?


Solution

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