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();
    }
}

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete