Ana*_*liy 26 c# generics castle-dynamicproxy async-await
我的问题与这篇文章有关拦截使用DynamicProxy调用异步方法
我想实现拦截器,它使用返回Task
或Task<T>
结果的异步方法.
我使用下一个代码返回ContinueWith
结果(以便在拦截器完成工作时调用方法等待)
var task = invocation.ReturnValue as Task;
invocation.ReturnValue = task.ContinueWith(c =>
{ code that should execute after method finish });
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常的Task
结果,但在的情况下,Task<T>
结果ContinueWith
将改变返回类型Task<T>
来Task
.我需要调用返回的重载方法ContinueWith Task<T>
,但为此我需要转换invocation.ReturnValue
为Task<T>
我没有找到以任何方式动态投射它的方法.有谁知道如何制作它?
我也尝试通过反射调用此方法,但参数是labmda函数,不能直接传递.
Sil*_*gel 22
经过广泛的研究,我能够创建一个解决方案,用于拦截同步方法以及异步任务和异步任务<TResult>.
下面是我使用Castle Dynamic Proxy处理所有这些方法类型的异常处理拦截器的代码.这种模式适用于进行任何你想要的拦截.对于标准的BeforeInvoke/AfterInvoke操作,语法会更清晰,但概念应该相同.
(其他注意:示例中的IExceptionHandler接口是自定义类型,而不是公共对象.)
private class AsyncExceptionHandlingInterceptor : IInterceptor
{
private static readonly MethodInfo handleAsyncMethodInfo = typeof(AsyncExceptionHandlingInterceptor).GetMethod("HandleAsyncWithResult", BindingFlags.Instance | BindingFlags.NonPublic);
private readonly IExceptionHandler _handler;
public AsyncExceptionHandlingInterceptor(IExceptionHandler handler)
{
_handler = handler;
}
public void Intercept(IInvocation invocation)
{
var delegateType = GetDelegateType(invocation);
if (delegateType == MethodType.Synchronous)
{
_handler.HandleExceptions(() => invocation.Proceed());
}
if (delegateType == MethodType.AsyncAction)
{
invocation.Proceed();
invocation.ReturnValue = HandleAsync((Task)invocation.ReturnValue);
}
if (delegateType == MethodType.AsyncFunction)
{
invocation.Proceed();
ExecuteHandleAsyncWithResultUsingReflection(invocation);
}
}
private void ExecuteHandleAsyncWithResultUsingReflection(IInvocation invocation)
{
var resultType = invocation.Method.ReturnType.GetGenericArguments()[0];
var mi = handleAsyncMethodInfo.MakeGenericMethod(resultType);
invocation.ReturnValue = mi.Invoke(this, new[] { invocation.ReturnValue });
}
private async Task HandleAsync(Task task)
{
await _handler.HandleExceptions(async () => await task);
}
private async Task<T> HandleAsyncWithResult<T>(Task<T> task)
{
return await _handler.HandleExceptions(async () => await task);
}
private MethodType GetDelegateType(IInvocation invocation)
{
var returnType = invocation.Method.ReturnType;
if (returnType == typeof(Task))
return MethodType.AsyncAction;
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
return MethodType.AsyncFunction;
return MethodType.Synchronous;
}
private enum MethodType
{
Synchronous,
AsyncAction,
AsyncFunction
}
}
Run Code Online (Sandbox Code Playgroud)
the*_*000 13
更好的解决方案是使用dynamic
关键字绕过编译器类型检查并在运行时解决操作:
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
var method = invocation.MethodInvocationTarget;
var isAsync = method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null;
if (isAsync && typeof(Task).IsAssignableFrom(method.ReturnType))
{
invocation.ReturnValue = InterceptAsync((dynamic)invocation.ReturnValue);
}
}
private static async Task InterceptAsync(Task task)
{
await task.ConfigureAwait(false);
// do the continuation work for Task...
}
private static async Task<T> InterceptAsync<T>(Task<T> task)
{
T result = await task.ConfigureAwait(false);
// do the continuation work for Task<T>...
return result;
}
Run Code Online (Sandbox Code Playgroud)
由于需要拦截返回的方法Task<TResult>
,我创建了一个扩展来Castle.Core
简化流程。
该包可在NuGet上下载。
该解决方案主要基于@silas-reinagel的回答,但通过提供一个新的接口来实现IAsyncInterceptor来简化它。还有进一步的抽象使拦截类似于实现Interceptor
。
有关更多详细信息,请参阅项目的自述文件。