Unity拦截器,拦截器被调用多次与部分类映射

本文关键字:映射 分类 调用 Unity | 更新日期: 2023-09-27 18:06:31

这几天我一直在寻找解决这个问题的办法,但没有运气。

基本上我们使用Unity做两件事:依赖注入和更重要的拦截。

我想要的是,拦截器是触发每次一个方法内部的部分类被调用,但我看到拦截器被调用几次,这取决于我在web上创建的映射的数量。配置,意味着2个映射,每个方法调用2个拦截。

在下面的代码示例中,所有部分类都具有相同的名称,但实现不同的接口,并且它们都驻留在不同的.cs文件中,这是因为该库将在短期内移动到WCF。所以我们有几个像这样的部分类:

public partial class PartialClass : IInterface1
{
   ...
}
public partial class PartialClass : IInterface2
{
   ...
}

配置文件如下:

<alias alias="IInterface1"     type="MyProject.Interface.IInterface1, MyProjectAssembly" />
<alias alias="IInterface2"     type="MyProject.Interface.IInterface1, MyProjectAssembly" />
<alias alias="PartialClass" type="MyProject.Services.PartialClass , MyProjectAssembly" />
<alias alias="Interceptor" type="MyProject.Services.Interceptor, MyProjectAssembly" />
<container>
extension type="Interception" />
<register type="IInterface1" mapTo="PartialClass">
    <lifetime  type="ContainerControlledLifetimeManager" />
    <interceptor type="InterfaceInterceptor"/>
    <interceptionBehavior type="Interceptor" />
</register> 
register type="IInterface2" mapTo="PartialClass">
    <lifetime  type="ContainerControlledLifetimeManager" />
    <interceptor type="InterfaceInterceptor"/>
    <interceptionBehavior type="Interceptor" />
</register> 
</container>

最后需要一个部分类实例的构造函数

public class MyClass()
{
    public MyClass(IInterface1 interface)
    {
         ...
    } 
    public MyClass()
    :this(Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IInterface1>(Container))
    {
    }
}

我遇到的问题是,拦截器被调用两次每个请求,这意味着,如果我添加更多的映射(Interface3, Interface4等),它将被调用3或4次取决于我添加的映射的数量。

Unity拦截器,拦截器被调用多次与部分类映射

如果您在其中一个注册中使用isDefaultForType元素,它将应用于该类型的所有注册。这将防止对处理程序的重复调用。例如

<register type="IInterface1" mapTo="PartialClass">
     <lifetime  type="ContainerControlledLifetimeManager" />
     <interceptor type="InterfaceInterceptor" isDefaultForType="True"/>
     <interceptionBehavior type="Interceptor" isDefaultForType="True"/>
</register> 
<register type="IInterface2" mapTo="PartialClass">
     <lifetime  type="ContainerControlledLifetimeManager" />
</register>