int ExecuteCommand(CommandDescription command, object optionInstance) { // get MethodInfo for the "Run" method var runMethod = GetRunMethod(command); // create command and execute it var commandInstance = m_CommandFactory.CreateCommandInstance(command.ImplementationType); var result = (int)runMethod.Invoke(commandInstance, new[] { optionInstance }); // call dispose if command implements IDisposable (commandInstance as IDisposable)?.Dispose(); return result; }
MethodInfo GetRunMethod(CommandDescription command) { var interfaceMapping = command.ImplementationType.GetInterfaceMap(typeof(ICommand<>).MakeGenericType(command.OptionType)); for (int i = 0; i < interfaceMapping.InterfaceMethods.Length; i++) { if (interfaceMapping.InterfaceMethods[i].Name == nameof(ICommand<object>.Run)) { return interfaceMapping.TargetMethods[i]; } } throw new ArgumentException($"Could not find Run() method for CommandDescription [{command}]. Make sure the implementation class implements {typeof(ICommand<>).Name}"); }