【问题标题】:Upgrading Unity container breaks interception mechanism升级 Unity 容器会破坏拦截机制
【发布时间】:2020-06-20 02:19:00
【问题描述】:

我们最近将项目中的 Microsoft Unity 从版本 3.5.1404 升级到了 5.8.6。只需对我们的代码进行一些小的调整,这次升级似乎就很容易了。它可以毫无问题地解决我们所有注册的实例。但是,我们还使用 Unity 的拦截机制来缓存方法以 AOP 样式返回的一些结果。这种缓存机制在升级后就被破坏了,我们不知道为什么。显然,当调用装饰方法时,我们的属性不再被调用。

它目前的工作方式如下。我们像这样注册拦截:

var container = new UnityContainer();
container.RegisterType<IService, Service>(some_lifetime);
container.AddNewExtension<Interception>();
container.Configure<Interception>()
         .SetInterceptorFor(typeof(IService), new InterfaceInterceptor());

在实现 IService 的 Service 类中,我们有一个用自定义 Cache 属性装饰的方法,如下所示:

public class Service : IService {
   [Cache(..)]
   public Result SomeMethod() {
      // Some code
   }
}

最后,我们自定义的 Cache 属性继承自 Unity 的 HandlerAttribute:

public class CacheAttribute : HandlerAttribute
{
    // ctor

    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return new CacheCallHandler(container, and, some, more);
    }
}

当方法 SomeMethod 过去在 3.5.1404 版本中被调用时,该属性被首先调用,但从 5.8.6 开始,它不再调用该属性。但是,代码确实可以编译。我们必须对其进行编译的更改主要是 usings 中的更改。比如Microsoft.Practices.Unity.InterceptionExtension 变成了Unity.Interception.PolicyInjection.Policies

我们无法弄清楚为什么这种机制不再起作用。即使在互联网上进行了广泛的研究之后,我们也找不到让它发挥作用的方法。因此,任何建议将不胜感激!

【问题讨论】:

    标签: unity-container aop interceptor


    【解决方案1】:

    我在尝试刷新一些遗留代码时遇到了完全相同的情况。我得到了它的工作:

    • 变化:

      • config.SetInterceptorFor(myType, new InterfaceInterceptor());
      • config.SetInterceptorFor(myType, new TransparentProxyInterceptor());
    • 注册继承自HandlerAttribute的类

      • Container.RegisterType&lt;MyHandlerAttribute&gt;(new PerRequestLifeTimeManager());
    • 注册每种类型以使用特殊的 InjectionMembers 进行拦截:

    Container.RegisterType<MyClassToBeIntercepted>(
        new Interceptor<TransparentProxyInterceptor>(),
        new InterceptionBehavior<PolicyInjectionBehavior>()
    );
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多