From 2225c28e001cb71bad55467c246332ebcefc87fc Mon Sep 17 00:00:00 2001 From: Simon G Date: Fri, 18 Sep 2020 22:37:17 +0200 Subject: [PATCH] - add GenericMethodCaller --- .../GenericMethodNotFoundException.cs | 17 ++++++++++ .../GenericMethodCaller.cs | 31 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 LightweightIocContainer/Exceptions/GenericMethodNotFoundException.cs create mode 100644 LightweightIocContainer/GenericMethodCaller.cs diff --git a/LightweightIocContainer/Exceptions/GenericMethodNotFoundException.cs b/LightweightIocContainer/Exceptions/GenericMethodNotFoundException.cs new file mode 100644 index 0000000..136eb24 --- /dev/null +++ b/LightweightIocContainer/Exceptions/GenericMethodNotFoundException.cs @@ -0,0 +1,17 @@ +// Author: Simon Gockner +// Created: 2020-09-18 +// Copyright(c) 2020 SimonG. All Rights Reserved. + +using System; + +namespace LightweightIocContainer.Exceptions +{ + public class GenericMethodNotFoundException : Exception + { + public GenericMethodNotFoundException(string functionName) + : base($"Could not find function {functionName}") + { + + } + } +} \ No newline at end of file diff --git a/LightweightIocContainer/GenericMethodCaller.cs b/LightweightIocContainer/GenericMethodCaller.cs new file mode 100644 index 0000000..799b4b7 --- /dev/null +++ b/LightweightIocContainer/GenericMethodCaller.cs @@ -0,0 +1,31 @@ +// Author: Simon Gockner +// Created: 2020-09-18 +// Copyright(c) 2020 SimonG. All Rights Reserved. + +using System; +using System.Reflection; +using LightweightIocContainer.Exceptions; + +namespace LightweightIocContainer +{ + public static class GenericMethodCaller + { + public static object Call(object caller, string functionName, Type genericParameter, BindingFlags bindingFlags, params object[] parameters) + { + MethodInfo method = caller.GetType().GetMethod(functionName, bindingFlags); + MethodInfo genericMethod = method?.MakeGenericMethod(genericParameter); + + if (genericMethod == null) + throw new GenericMethodNotFoundException(functionName); + + try //exceptions thrown by methods called with invoke are wrapped into another exception, the exception thrown by the invoked method can be returned by `Exception.GetBaseException()` + { + return genericMethod.Invoke(caller, parameters); + } + catch (Exception ex) + { + throw ex.GetBaseException(); + } + } + } +} \ No newline at end of file