开发者

Why is this method call not getting intercepted?

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>().SetI开发者_开发技巧nterceptorFor<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);
        }

    }

}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜