Unity的基于代码的拦截/日志记录配置

时间:2011-05-25 21:47:03

标签: .net logging unity-container ioc-container unity-interception

我使用Unity作为IoC容器,到目前为止工作正常。现在我想使用TypeMatchingRule和LogCallHandler进行拦截,以记录对IMyInterface接口的所有调用。我通过代码配置统一,但无法使用日志工作。有人能指出我的简单例子吗?我在文档中发现了一些小的片段,但是我无法为我的用例构建一个有效的配置。好像我错过了大局!?

2 个答案:

答案 0 :(得分:4)

首先,做一个行为。这是一个例子:

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())
        );

它将跟踪记录器中的每个调用

答案 1 :(得分:0)

如果你想在拦截注册中添加调用处理程序,你需要做这样的事情(我试着让变量名不言自明):

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());
相关问题