Code Based Interception / Registration Configuration for Unity

Im uses Unity as an IoC container that still works. Now I would like to use interception using TypeMatchingRule and LogCallHandler to register all calls to the IMyInterface interface. I am setting up unity with code, but can't get logging to work. Can someone point me to a simple example? I found quite small snippets in the documentation, but I cannot create a working configuration for my use case. Looks like I'm missing a big picture !?

+3
source share
2 answers

First of all, do the 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 track every call in the log.

+4

, - ( ):

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

All Articles