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 loggi开发者_如何学JAVAng 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!?
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
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());
精彩评论