1

几天来,我一直在寻找解决此问题的方法,但没有运气。

基本上我们将 Unity 用于两件事:依赖注入,更重要的是用于拦截。

我想要的是每次调用部分类中的方法时都会触发拦截器,但是我看到根据我在 web.config 上创建的映射数量,拦截器被调用多次,这意味着 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 次,具体取决于我添加的映射数量。

4

1 回答 1

0

如果您在其中一个注册上使用 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> 
于 2015-10-15T22:06:54.870 回答