Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Method interceptors in depth

Acoustic edited this page Sep 14, 2010 · 1 revision

Method interceptors are slightly more advanced than simply behaving as a proxy wrapper. As of the current build, interceptors can opt to support a “BeforeInvocation” and an “AfterInvocation” method. As the need arises, more methods, events, delegates, whatever… will be built out. This is why Snap is a powerful framework.

Overriding these methods allows you more control over how your interceptor behaves. In some ways, this pattern is similar to a constructor/destructor method, or a unit test’s setup/tear down method. It’s affording you flexibility to act independent of the impending target method invocation.

Here’s a simple sample for measuring execution duration. Yes, this could be done all within one method; it’s just an example.

public class MeasureDurationInterceptor : MethodInterceptor
{
    private DateTime _start;
    // Called before InterceptMethod
    public override void BeforeInvocation()
    {
        _start = DateTime.Now;
    }
    public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
    {
        // Elided
    }
    // Called after InterceptMethod
    public override void AfterInvocation()
    {
        var duration = DateTime.Now - _start;
        // Do something meaningful with the result.
    }
}

Happy coding!

Clone this wiki locally