protected void AddResultHook <TBaseRequest, TResult>(IResultHook <TBaseRequest, TResult> hook)
        {
            if (!typeof(TBaseRequest).IsAssignableFrom(typeof(TRequest)))
            {
                throw new ContravarianceException(nameof(AddResultHook), typeof(TBaseRequest), typeof(TRequest));
            }

            ResultHooks.Add(InstanceResultHookFactory.From(hook));
        }
예제 #2
0
 internal static InstanceResultHookFactory From <TRequest, TResult>(
     IResultHook <TRequest, TResult> hook)
 {
     return(new InstanceResultHookFactory(
                hook,
                new FunctionResultHook(typeof(TResult),
                                       (request, result, ct) => hook
                                       .Run((TRequest)request, (TResult)result, ct)
                                       .ContinueWith(t => (object)t.Result))));
 }
예제 #3
0
        /// <summary>
        /// Adds a result hook instance.
        /// </summary>
        public void AddResultHook(IResultHook hook)
        {
            var hookType = hook.GetType();

            var baseHookType = hookType
                               .GetBaseTypes()
                               .SingleOrDefault(x =>
                                                x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ResultHook <,>));

            if (baseHookType == null)
            {
                throw new ArgumentException($"Unable to add '{hookType}' as a result hook for '{typeof(TRequest)}'.\r\n" +
                                            $"Result hooks must inherit ResultHook<TRequest, TResult>.");
            }

            var requestType = baseHookType.GenericTypeArguments[0];

            if (!requestType.IsAssignableFrom(typeof(TRequest)))
            {
                throw new ContravarianceException(nameof(AddResultHook), requestType, typeof(TRequest));
            }

            var resultType = baseHookType.GenericTypeArguments[1];

            var factoryMethod = typeof(InstanceResultHookFactory)
                                .GetMethod(nameof(InstanceResultHookFactory.From), BindingFlags.NonPublic | BindingFlags.Static)
                                .MakeGenericMethod(requestType, resultType);

            try
            {
                AddResultHook((IResultHookFactory)factoryMethod.Invoke(null, new object[] { hook }));
            }
            catch (TargetInvocationException e)
            {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }

                throw e;
            }
        }