Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code based interception/logging configuration for Unity

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!?

like image 626
Achim Avatar asked Jun 09 '26 10:06

Achim


1 Answers

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

like image 184
onof Avatar answered Jun 11 '26 23:06

onof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!