2011-08-23 147 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>