skip to the main content area of this page
Patterns and Practices

 

VirtualMethodInterceptor in Unity v1.2 - For Those Castle DynamicProxy Fans...


I have to say that I am starting to like Unity more and more everyday. Included in Unity v1.2 is the new Interception Extension and two interceptors: TransparentProxyInterceptor and VirtualMethodInterceptor. The TransparentProxyInterceptor is similar to the functionality in the Enterprise Library Policy Injection Application Block. The VirtualMethodInterceptor reminds me of Castle's DynamicProxy.

You can read more about the TransparentProxyInterceptor at:

 

VirtualMethodInterceptor

Just as the name suggests, it appears the VirtualMethodInterceptor will allow you to intercept virtual methods on classes just like Castle's DynamicProxy. These classes need to be public and not sealed.

Here is a contrived example that uses the VirtualMethodInterceptor to intercept the Virtual Write Method on a Logger Class:

 

using System;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.InterceptionExtension;

 

namespace VirtInterceptorExample

{

    class Program

    {

        static void Main(string[] args)

        {

            IUnityContainer container = new UnityContainer();

            container.AddNewExtension<Interception>();

 

            container.RegisterType<Logger>();

            container.Configure<Interception>().

                SetInterceptorFor<Logger>(new VirtualMethodInterceptor());

 

            var logger = container.Resolve<Logger>();

            logger.Write("World.");

        }

    }

 

    public class Logger

    {

        [Test]

        public virtual void Write(string message)

        {

            Console.Write(message);

        }

    }

 

    public class TestAttribute : HandlerAttribute

    {

        public override ICallHandler CreateHandler(IUnityContainer container)

        {

            return new TestHandler();

        }

    }

 

    public class TestHandler : ICallHandler

    {

        public int Order { get; set; }

 

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)

        {

            Console.Write("Hello, ");

            return getNext()(input, getNext);

        }

    }

}

 

When you run the console application it will display "Hello, World." Cheesy, I know :)

Hope this helps,

David Hayden

 

 

Conclusion

This is a very high-level use of the VirtualMethodInterceptor, but if you take a peek at some of the unit tests you can see some low-level uses as well which I will show off next time.

 

 

Unity Tutorials

 

Check out other Unity Tutorials and Unity Webcasts

 


Tags: DependencyInjection, IoC, Unity


Topics



 

Popular Tags



Recent Links