2011-08-23 89 views
1

我一直在四处寻找这个修复了几天,没有运气多次调用。团结拦截,拦截器与部分类映射

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

我想要的是每次调用partial类中的一个方法时都会触发拦截器,但是我看到Interceptor被调用了好几次,这取决于我在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)) 
    { 

    } 
} 

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

回答

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>