views:

152

answers:

1

Why doesn't DoIt() method call get intercepted? Should I use something other than InterfaceInterceptor to intercept the DoIt() method? How would you do it?

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

namespace UnityTest
{
    class Program
    {
     static void Main(string[] args)
     {
      IUnityContainer container = new UnityContainer();
      container.AddNewExtension<Interception>();
      container.RegisterType<ILogger, Logger>();
      container.Configure<Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor());

      var logger = container.Resolve<ILogger>();
      logger.Write("World.");
      Console.ReadKey();

     }
    }

    public interface ILogger
    {
     void Write(string message);

     [Test]
     void DoIt(string message);
    }


    public class Logger : ILogger
    {
     public void Write(string message)
     {
      DoIt(message);
     }

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

    }

}
+2  A: 

You need to apply the [Test] attribute to ILogger.Write instead of DoIt. The way interception works is to create a transparent proxy which then passes control to any handlers before the target method. The problem with your current setup is that DoIt is called by the logger instance itself, so there is no way for the proxy to intercept the call. In other words, you can only intercept methods called directly on an interface when using interception.

Lee
Could I do it with Instance or Type interception? Because I need to intercept a method that is being called by the interface itself like it the example.
subjective-c
Yes you might be able to make Logger.DoIt virtual and create an instance inteceptor on Logger. I think Unity might have had problems with nested proxies like that, but 2.0 might have fixed it...
Lee