Use Unity to intercept all calls to IMyInterface.SomeMethod

Vaccano picture Vaccano · Aug 10, 2012 · Viewed 12.6k times · Source

I am trying to learn Unity Interceptors and I am having a hard go of it.

Say I have an interface like this:

public interface IMyInterface
{
   void SomeMethod();
}

And I have an unknown number of classes that implement that interface like this:

public class SpecificClass1 : IMyInterface
{
   public void SomeMethod()
   {
       Console.WriteLine("Method Called");
   }
}

I am looking for a way to say, "for all instance of IMyInterface (I don't want to enumerate them), when SomeMethod is called run my interceptor.

It is the Non-Enumeration of the classe that is giving me trouble. (There are plenty of examples if you can enumerate all your classes.)

I have read of Type Interception, but I can't seem to find out if it will do what I am looking for.

Any Unity experts out there know how to do what I am looking for?

Answer

GSerjo picture GSerjo · Aug 10, 2012

You could create InterceptionBehavior then register it on specific class. Note you could filter executing methods in Invoke thru IMethodInvocation input

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using NUnit.Framework;

namespace UnitTests
{
    [TestFixture]
    public class ForTest
    {
        [Test]
        public void Test()
        {
            IUnityContainer container = new UnityContainer().AddNewExtension<Interception>();
            container.RegisterType<IMyInterface, SpecificClass1>(
                new Interceptor<InterfaceInterceptor>(),
                new InterceptionBehavior<MyInterceptionBehavior>());
            var myInterface = container.Resolve<IMyInterface>();
            myInterface.SomeMethod();
        }
    }

    public interface IMyInterface
    {
        void SomeMethod();
    }

    public class SpecificClass1 : IMyInterface
    {
        #region IMyInterface

        public void SomeMethod()
        {
            Console.WriteLine("Method Called");
        }

        #endregion
    }

    public class MyInterceptionBehavior : IInterceptionBehavior
    {
        public bool WillExecute
        {
            get { return true; }
        }

        #region IInterceptionBehavior

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Enumerable.Empty<Type>();
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn result = getNext()(input, getNext);
            Console.WriteLine("Interception Called");
            return result;
        }

        #endregion
    }
}

Console output

Method Called
Interception Called

More about Interception with Unity