【问题标题】:Configure unity interception after container initialization容器初始化后配置unity拦截
【发布时间】:2011-07-29 17:46:04
【问题描述】:

我有一个通过 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 方法的调用都通过此行为。我该怎么做?

【问题讨论】:

    标签: c# asp.net-mvc-3 unity-container interception


    【解决方案1】:

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

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

    【讨论】:

    • 但是我可以向已经注册的组件添加行为吗?我只找到了添加注册时间行为的方法...
    • 当然,只需调用 container.RegisterType(new InterceptionBehavior(...));再次。它添加到现有注册,而不是覆盖它。
    • 太棒了!谢谢!我以为它又注册了类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2012-10-03
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多