private Func <IInvocation, Task> CreateMethod(MethodInfo method) { var returnType = method.ReturnType; if (!typeof(Task).IsAssignableFrom(returnType)) { throw new InvalidOperationException($"Hub invocation method `{method.Name}` must return a Task"); } if (returnType == typeof(Task)) { return(inv => connection.SendAsync(method.Name, inv.Arguments)); } else if (returnType.GetGenericTypeDefinition() == typeof(Task <>)) { var actualReturnType = returnType.GetGenericArguments().Single(); var castMethod = TaskCastMethod.MakeGenericMethod(new[] { actualReturnType }); return(inv => { var res = connection.InvokeAsync(method.Name, inv.Arguments, actualReturnType); return (Task)castMethod.Invoke(null, new[] { res }); }); } throw new InvalidOperationException($"Task is assignable from {returnType}, but is not a Task, nor Task<>, should never happen"); }