对于我的一个 DAL 模块,我有很多重复的管道,形状如下:
while (retry)
{
...
try
{
...do something
retry = false;
}
catch (SqlException sqlEx)
{
// Retry only if -2 = Connection Time Out or 1205 = Deadlock
if (sqlEx.Number == -2 || sqlEx.Number == 1205)
{
..retry if attempt < max
}
..log and rethrow exception
}
}
并且最近发现了 PostSharp,我试图用一个属性替换这些管道代码。
我最初的计划是: - 扩展 OnMethodInvocationAspect 并在方法调用期间记住方法调用事件 args - 实现 IOnExceptionAspect 并实现 OnException 以检查异常类型,如果需要重试,请使用原始调用中的方法调用事件 args 对象,即:
[Serializable]
public sealed class RetryAttribute : OnMethodInvocationAspect, IOnExceptionAspect
{
[NonSerialized]
private MethodInvocationEventArgs m_initialInvocationEventArgs = null;
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
if (m_initialInvocationEventArgs == null)
m_initialInvocationEventArgs = eventArgs;
base.OnInvocation(eventArgs);
}
public void OnException(MethodExecutionEventArgs eventArgs)
{
// check if retry is necessary
m_initialInvocationEventArgs.Proceed();
}
}
但是一旦我添加了 IOnExceptionAspect,就不会再触发 OnInvocation 方法了。
有谁知道我需要在这里做什么?或者也许我应该使用更合适的方面?
谢谢,