3

Im using Unity as IoC container which works fine so far. Now I would like to use interception with a TypeMatchingRule and a LogCallHandler to log all calls to an interface IMyInterface. I'm configuring unity via code, but cannot get logging to work. Could somebody point me to simple example? I found quite some small snippets in the documentation, but I'm not able build a working configuration for my use case. Seems like I'm missing the big picture!?

Steven
  • 166,672
  • 24
  • 332
  • 435
Achim
  • 15,415
  • 15
  • 80
  • 144

2 Answers2

4

First of all, make a behavior. Here is an example:

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; }
    }
  }

then, register it:

Container
        .AddNewExtension<Interception>()
        .RegisterType<IDao, NhDao>(new Interceptor(new InterfaceInterceptor()),
                new InterceptionBehavior(new MyLoggerBehavior())
        );

It will trace every call in the logger

onof
  • 17,167
  • 7
  • 49
  • 85
  • That's the direction I'm looking for, but I would like to use the Logging block of Enterprise Library 5.0, which has already all required classes. My questions aims at getting your results by using the build in classes. – Achim May 31 '11 at 09:34
0

If you want to add the add the call handler to the interception registration, you need to do something like this (I tried to make the variable names self-explanatory):

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());
code4life
  • 15,655
  • 7
  • 50
  • 82