目录
1.2 /// Intercept the invocation
private void SetParameters(T decorated, IContextProvider contextProvider, IAttributeProvider attributeProvider)
{
_decorated = decorated;
_contextProvider = contextProvider ?? throw new ArgumentNullException(nameof(contextProvider));
_attributeProvider = attributeProvider ?? throw new ArgumentNullException(nameof(attributeProvider));
}
/// <summary>
/// </summary>
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
var methodParameterTypes = targetMethod.GetParameters().Select(p => p.ParameterType).ToArray();
var classMethodInfo = _decorated != null
? _decorated.GetType().GetMethod(targetMethod.Name, methodParameterTypes)
: targetMethod;
var invocation = new Invocation
{
Arguments = args,
GenericArguments = targetMethod.IsGenericMethod ? targetMethod.GetGenericArguments() : new Type[0],
InvocationTarget = _decorated,
Method = targetMethod,
Proxy = this,
MethodInvocationTarget = classMethodInfo,
TargetType = _decorated != null ? _decorated.GetType() : typeof(T)
};
var methodExecutingContext = new MethodExecutingContext
{
InvocationContext = _contextProvider.GetContext(),
MethodInfo = targetMethod,
Invocation = invocation
};
var attributes = GetInvocationMethodFilterAttributes(invocation, methodExecutingContext.InvocationContext);
if (attributes.Any(a => a is NoInterceptAttribute))
{
invocation.Proceed();
return invocation.ReturnValue;
}
var methodFilterAttributes = attributes.OfType<MethodFilterAttribute>().OrderBy(x => x.Order).ToList();
var exceptionFilterAttributes = attributes.OfType<ExceptionFilterAttribute>().ToList();
var isAsync = typeof (Task).IsAssignableFrom(invocation.Method.ReturnType);
if (isAsync)
{
if (invocation.Method.ReturnType.IsGenericType && invocation.Method.ReturnType.GetGenericTypeDefinition() == typeof (Task<>))
{
var taskResultType = invocation.Method.ReturnType.GetGenericArguments()[0];
var mInfo = HandleAsyncWithTypeMethod.MakeGenericMethod(taskResultType);
if (_decorated != null)
{
methodFilterAttributes.Add(new InvocationAttribute(invocation, taskResultType));
}
invocation.ReturnValue = mInfo.Invoke(this, new object[] { methodFilterAttributes, exceptionFilterAttributes, methodExecutingContext });
}
else
{
if (_decorated != null)
{
methodFilterAttributes.Add(new InvocationAttribute(invocation));
}
invocation.ReturnValue = HandleAsync(methodFilterAttributes, exceptionFilterAttributes, methodExecutingContext);
}
}
else
{
if (_decorated != null)
{
methodFilterAttributes.Add(new InvocationAttribute(invocation));
}
HandleSync(methodFilterAttributes, exceptionFilterAttributes, methodExecutingContext);
}
return invocation.ReturnValue;
}