2

我有一个通过 XML 文件配置的统一容器。配置完成后,我想通过代码为某些类型添加一些拦截。如何才能做到这一点?我有以下行为:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity.InterceptionExtension;
using NLog;

namespace WebDibaelsaMVC.Utils.Behaviors
{
    public class LoggingBehavior : IInterceptionBehavior
    {
        private readonly Logger _log = LogManager.GetLogger("Unity");

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var msg = getNext()(input, getNext);
            if (msg.Exception != null)
                _log.ErrorException("Error d'unity.", msg.Exception);
            return msg;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return new[] {typeof (IController)};
        }

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

我希望所有对通过容器解析的类型的 IController 方法的调用都通过这种行为。我该怎么做?

4

1 回答 1

4

加载配置后只需调用配置 API。“配置时间”没有什么神奇之处;Unity 的规则是“最后配置获胜”。因此,您可以从 XML 加载,使用 API 进行操作,然后加载第二个 XML 部分,它们将一起加载。

如果您在 MVC 中使用拦截,请注意,真正让它正常工作的唯一方法是使用 VirtualMethodInterceptor;使用实例拦截器还需要自定义操作调用程序才能使一切正常工作(相信我,我已经尝试过)。

于 2011-04-07T05:19:20.137 回答