抱歉标题可能有些模糊,但我想要实现的目标通过代码更好地表述。
我有一个WCF客户端,当我调用方法时,我希望每个调用都被包装在一些错误处理代码中。因此,我没有直接暴露方法,而是在客户端类上创建了以下辅助函数:
public T HandleServiceCall<T>(Func<IApplicationService, T> serviceMethod)
{
try
{
return serviceMethod(decorator);
}
[...]
}
客户端代码使用它如下:
service.HandleServiceCall(channel => channel.Ping("Hello"));
调用Ping方法的过程被封装在一些逻辑中,以便尝试处理任何错误。
这很好用,但我现在有一个需求,需要知道实际上在服务上调用了哪些方法。最初,我希望使用表达式树来检查Func<IApplicationService, T>
,但进展不大。
最后,我采用了装饰器模式:
public T HandleServiceCall<T>(Func<IApplicationService, T> serviceMethod)
{
var decorator = new ServiceCallDecorator(client.ServiceChannel);
try
{
return serviceMethod(decorator);
}
[...]
finally
{
if (decorator.PingWasCalled)
{
Console.Writeline("I know that Ping was called")
}
}
}
装饰器本身:
private class ServiceCallDecorator : IApplicationService
{
private readonly IApplicationService service;
public ServiceCallDecorator(IApplicationService service)
{
this.service = service;
this.PingWasCalled = new Nullable<bool>();
}
public bool? PingWasCalled
{
get;
private set;
}
public ServiceResponse<bool> Ping(string message)
{
PingWasCalled = true;
return service.Ping(message);
}
}
这段代码非常笨重,而且需要写很多行。 有没有更加优雅的方法可以实现同样的功能呢?
HandleServiceMethod
在同一父类中。 - djskinnerFunc
转换为Expression
。 - djskinner