【发布时间】:2015-09-01 09:11:50
【问题描述】:
我正在尝试开发一个自定义属性来装饰方法,当我这样做时,我希望它们被属性“捕获”,因此它决定如何处理异常。
我特别知道有两种技术可以做到这一点: - PostSharp - 企业图书馆统一
我想避免第一个,我想继续使用 Unity,因为我们已经在使用 Enterprise Library。
所以,为了完成这项工作,我做了以下工作:
我的呼叫处理程序:
public class LoggingCallHandler : ICallHandler
{
public bool Rethrow
{
get; set;
}
public bool Log
{
get; set;
}
public int Order
{
get; set;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
var result = getNext().Invoke(input, getNext);
if (result.Exception != null)
{
if (this.Rethrow)
throw result.Exception;
if (this.Log)
this.LogException(result.Exception);
}
return result;
}
private void LogException(Exception ex)
{
// Do stuff
}
}
我的自定义属性
public class LoggingCallHandlerAttribute : HandlerAttribute
{
private bool rethrow;
private bool log;
public LoggingCallHandlerAttribute(bool rethrow, bool log = false)
{
this.rethrow = rethrow;
this.log = log;
}
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LoggingCallHandler() { Rethrow = this.rethrow, Log = this.log };
}
}
我的类带有用属性修饰的方法
public class TestManager
{
[LoggingCallHandler(false, false)]
public void DoStuff()
{
throw new Exception("TEST");
}
}
当我运行该方法时,没有发生 AOP。
我知道 Unity 可能依赖或完全依赖容器。但是我们目前不使用任何一个,所以我们只想用 [LoggingCallHandler] 属性来装饰一个方法,就是这样。
如果容器确实需要,可以考虑,但最好有一个适合所有用途的容器(至少现在......)。
有可能实现吗?
谢谢你们。
【问题讨论】:
标签: c# unity-container aop