考虑以下,它的工作原理:
public interface IService
{
void DoSomething(object arg);
void DoSomethingElse(object arg, bool anotherArg);
bool AndDoYetMoreStuff(object arg, object[] moreArgs);
}
public class Service : IService
{
public void DoSomething(object arg){}
public void DoSomethingElse(object arg, bool anotherArg){}
public bool AndDoYetMoreStuff(object arg, object[] moreArgs)
{
return true;
}
}
public class ServiceRetryProxy : IService
{
const int retryLimit = 3;
private readonly IService _service;
public ServiceRetryProxy(IService service)
{
_service = service;
}
private void RetryOnException(Action<IService> ctx)
{
ReconnectOnException(service =>
{
ctx(service);
return new object();
});
}
private T RetryOnException<T>(Func<IService, T> ctx)
{
var counter = 0;
Exception lastException = null;
while (counter < retryLimit)
{
try
{
return ctx(_service);
}
catch (Exception ex)
{
lastException = ex;
counter++;
}
}
throw lastException;
}
public void DoSomething(object arg)
{
ReconnectOnException(x => x.DoSomething(arg));
}
public void DoSomethingElse(object arg, bool anotherArg)
{
ReconnectOnException(x => x.DoSomethingElse(arg, anotherArg));
}
public bool AndDoYetMoreStuff(object arg, object[] moreArgs)
{
return ReconnectOnException(x => x.AndDoYetMoreStuff(arg, moreArgs));
}
}
这样做的问题是我必须为接口的每个方法编写一个代理方法。我想要一个更“动态”的解决方案,以便我可以将 RetryOnException(或任何其他逻辑)应用于任何给定接口上的每个方法。我目前正在查看 Castle DynamicProxy,但如果有其他选项怎么办?