internal static InstanceRequestHookFactory From <TRequest>( IRequestHook <TRequest> hook) { return(new InstanceRequestHookFactory( hook, new FunctionRequestHook((request, ct) => hook.Run((TRequest)request, ct)))); }
protected void AddRequestHook <TBaseRequest>(IRequestHook <TBaseRequest> hook) { if (!typeof(TBaseRequest).IsAssignableFrom(typeof(TRequest))) { throw new ContravarianceException(nameof(AddRequestHook), typeof(TBaseRequest), typeof(TRequest)); } RequestHooks.Add(InstanceRequestHookFactory.From(hook)); }
/// <summary> /// Adds a request hook instance. /// </summary> public void AddRequestHook(IRequestHook hook) { var hookType = hook.GetType(); var baseHookType = hookType .GetBaseTypes() .SingleOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(RequestHook <>)); if (baseHookType == null) { throw new ArgumentException($"Unable to add '{hookType}' as a request hook for '{typeof(TRequest)}'.\r\n" + $"Request hooks must inherit RequestHook<TRequest>."); } var requestType = baseHookType.GenericTypeArguments[0]; if (!requestType.IsAssignableFrom(typeof(TRequest))) { throw new ContravarianceException(nameof(AddRequestHook), requestType, typeof(TRequest)); } var factoryMethod = typeof(InstanceRequestHookFactory) .GetMethod(nameof(InstanceRequestHookFactory.From), BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(requestType); try { AddRequestHook((IRequestHookFactory)factoryMethod.Invoke(null, new object[] { hook })); } catch (TargetInvocationException e) { if (e.InnerException != null) { throw e.InnerException; } throw e; } }