问题描述
|
我使用Unity作为IoC容器,到目前为止效果良好。现在,我想将拦截与TypeMatchingRule和LogCallHandler一起使用,以记录对接口IMyInterface的所有调用。我正在通过代码配置统一性,但无法启动日志记录。有人可以指出简单的例子吗?我在文档中找到了一些小片段,但是我无法为我的用例构建有效的配置。好像我错过了大局!?
解决方法
首先,做个行为。这是一个例子:
public class MyLoggerBehavior : IInterceptionBehavior
{
public IMethodReturn Invoke(IMethodInvocation input,GetNextInterceptionBehaviorDelegate getNext)
{
var returnValue = getNext()(input,getNext);
if (returnValue.Exception != null)
{
Global.Logger.TraceException(\"Exception intercepted\",returnValue.Exception);
}
else
{
Global.Logger.Trace(\"Method {0} returned {1}\",input.MethodBase,returnValue.ReturnValue);
}
return returnValue;
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return new Type[0];
}
public bool WillExecute
{
get { return Global.Logger.IsTraceEnabled; }
}
}
然后,注册:
Container
.AddNewExtension<Interception>()
.RegisterType<IDao,NhDao>(new Interceptor(new InterfaceInterceptor()),new InterceptionBehavior(new MyLoggerBehavior())
);
它将跟踪记录器中的每个呼叫
,如果要将add调用处理程序添加到拦截注册中,则需要执行以下操作(我试图使变量名不言自明):
var intp = m_singleInstance.Configure<Interception>()
.SetInterceptorFor(typeof(typeToIntercept),new TransparentProxyInterceptor());
var policy = intp.AddPolicy(policyNameString);
policy.AddMatchingRule<TypeMatchingRule>(
new InjectionConstructor(
new InjectionParameter(typeof(typeToIntercept))))
.AddCallHandler(typeof(LogCallHandler),new ContainerControlledLifetimeManager());