Skip to main content

Interception with LinFu

I have previously showed you how you can do interception with both Castle DynamicProxy and with Unity. Now it is time to do the same with LinFu, which is suprisingly easy if you have done it with the previous two.

Implement the IInvokeWrapper

There are several ways for interception with LinFu but I like the InvokeWrapper, because it's so easy to use. Just implement the LinFu.AOP.Interfaces.IInvokeWrapper.

public class MyInvokeWrapper : IInvokeWrapper
{
 private readonly IBookRepository target;
 public MyInvokeWrapper(IBookRepository target)
 {
  this.target = target;
 }

public void BeforeInvoke(IInvocationInfo info) { Debug.WriteLine("Before {0}", new[] { info.TargetMethod.Name }); }

public void AfterInvoke(IInvocationInfo info, object returnValue) { Debug.WriteLine("After {0}", new[] { info.TargetMethod.Name }); }

public object DoInvoke(IInvocationInfo info) { Debug.WriteLine("Invoking {0}", new[] { info.TargetMethod.Name }); return info.TargetMethod.Invoke(target, info.Arguments); } }

Now that's quite self explanatory.

Create a new ProxyFactory and intercept away

Now all you need to do to get your proxy class is the following.

var factory = new ProxyFactory();
var repository = new StoreRepository();
var myInterceptor = new MyInvokeWrapper(repository);

return factory.CreateProxy<IBookRepository>(myInterceptor)));

Go here for a full example , or download as a zip archive.

comments powered by Disqus