2011-11-18 58 views
1

早上,結構圖 - 爲新接口註冊舊接口的包裝

在代碼庫中我維護着一箇舊接口。我們稱之爲IFoo。它幾乎變得過時了,幾周前用Interface INewFoo進行了更換,但爲了向後兼容,我編寫了一個包裝類,它實現了INewFoo並在構造函數中使用了IFoo。

爲了澄清,請考慮以下代碼。

Public Interface IFoo 
     Sub DoStuff() 
    End Interface 

    Public Interface INewFoo 
     Sub DoPrettyMuchTheSameStuff() 
    End Interface 

    Public Class FooToNewFooWrapper 
     Implements INewFoo 

     Private _foo As IFoo 
     Public Sub New(foo As IFoo) 
     _foo = foo 
     End Sub 

     Public Sub DoPrettyMuchTheSameStuff() Implements INewFoo.DoPrettyMuchTheSameStuff 
     _foo.DoStuff() 
     End Sub 
    End Class 

對於這兩個接口,通過使用StructureMap掃描一些程序集來加載實現。

現在,我們來看看壞事。因爲我無法理解和改變,舊界面的大多數實現都被放入表單中。因爲這些往往是顯示和處置,我必須創建一個新的實例,每次我使用ObjectFactory.GetAllInstances(IFoo)。這仍然沒有問題,但我想爲IFoo的每個註冊實現註冊一個INewFoo-Wrapper,這樣我就可以使用ObjectFactory.GetAllInstances(INewFoo)並獲得IFoo和INewFoo的所有實現。

我無法遍歷IFoo的實現併爲每個實現註冊一個包裝,因爲據我所知,您可以只註冊那些實例。

下面錯誤代碼:

ObjectFactory.Configure(Sub(config) 
          config.Scan(Sub(scan) 
              For Each ass In assemblies 
              scan.Assembly(ass) 
              Next 
              scan.AddAllTypesOf(Of IFoo)() 
             End Sub) 
          End Sub) 

Dim oldImplementations = ObjectFactory.GetAllInstances(Of IFoo)() 

    ObjectFactory.Configure(Sub(config) 
          For Each implementation In oldImplementations 
           Dim notIterated = implementation 
           config.For(Of INewFoo).Add(Function(x) New FooToNewFooWrapper(notIterated)) 
          Next 
          End Sub) 

我的問題是:是否可以註冊一個包裝器的IFoo的每個實現創建包裝的一個新實例之前,它總是會創建一個新的執行實例?

在C#和Vb.net中的答案同樣受到歡迎。

回答

2

您是否嘗試過實施自定義註冊慣例來執行您的特定要求?海關注冊公約允許非常靈活的掃描和註冊

[CLSCompliant(false)] 
public class MyRegistration : IRegistrationConvention 
/// <inheritdoc /> 
    public void Process(Type type, Registry registry) 
    {   

     Type interfaceType = type.GetInterface(typeof(IFoo).Name); 
     if (interfaceType == null) 
     { 
      return; 
     } 

     registry.AddType(interfaceType, type, type.Name); 

     // Do your stuff with INewFoo 

    } 
} 

配置結構圖使用掃描儀:

ObjectFactory.Configure(item => 
      { 
       item.Scan(
        x => 
        { 
         x.AssembliesFromPath("c:\wheremyassemblyis.dll"); 
         x.With(new MyRegistration()); 
        }); 
      }); 
+0

花了一點時間讓我嘗試一下,但還是有一些解決方法,我管理做到這一點。 – Lambda