Wednesday, April 17, 2013

Unity IoC with interception

I'm used to working with Ninject for dependency injection, but for work I have to dig into Unity and use it for a WCF service. I want NLog logging using interceptors, so I had to wire that stuff up a bit.

Here's a quick proof-of-concept of getting Unity to intercept method calls.


namespace UnityConsole
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.InterceptionExtension;

    internal class Program
    {
        private static void Main(string[] args)
        {
            // Instantiate the Unity Container
            IUnityContainer container = new UnityContainer();

            // Enable Interception
            container.AddNewExtension<Interception>();
            
            // Register the service and the interceptor
            container.RegisterType<IService, MyService>(
                new Interceptor(new InterfaceInterceptor()), new InterceptionBehavior(typeof(MyBehavior)));
            
            // Get the service from the container
            var myService = container.Resolve<IService>();

            // Invoke the method
            myService.SayHi();

            // Prevent screen from closing
            Console.ReadLine();
        }
    }

    public class MyBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // PRE execution logging
            System.Diagnostics.Debug.WriteLine("Executing method named: " + input.MethodBase.Name);

            // Continue method call
            var result = getNext()(input, getNext);

            // POST execution logging
            System.Diagnostics.Debug.WriteLine("Method execution done - resulted in value: " + result.ReturnValue);

            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            // Empty - so no restrictions here 
            return new Type[] { };
        }

        public bool WillExecute
        {
            get
            {
                return true;
            }
        }
    }

    public class MyService : IService
    {
        public string SayHi()
        {
            return "Hi there buddy";
        }
    }

    public interface IService
    {
        string SayHi();
    }
}

No comments:

Post a Comment