2011-08-24 74 views
3

我有組件的層次結構如下:如何添加屬性到現有的界面?

MyRoot 
MyRoot.General 
MyRoot.General.Model 
MyRoot.General.MyApp 

每個組件應引用來自MyApp的下降到MyRoot。換句話說,MyRoot不應該引用任何這些程序集。 MyApp可以引用所有這些。

MyRoot.General包含一個名爲IMyContext的接口。在Model和MyApp命名空間中使用IMyContext在應用程序實例的生命週期中提供實例數據。問題是我需要將另一個屬性添加到IMyContext,以便模型命名空間中的類實例可以通過Model和MyApp命名空間(就像IMyContext實例一樣)。但是,然後MyRoot.General將不得不引用MyRoot.General.Model程序集。我可以在Model中爲這個類創建一個單例,但是我基本上有兩個上下文來跟上 - IMyContext和MyRoot.General.Model.MySingleton。

有沒有更好的方法來做到這一點?我想這可能是某種類型的作品。

此外,現有應用程序正在使用MyRoot.General.IMyContext。如果將新屬性添加到IMyContext,將會導致重構和風險過高。

回答

2

爲什麼不在MyRoot.General中定義您需要的類的接口,然後在MyRoot.General.Model中提供該接口的實現。您大概已經在IMyContext的周圍傳遞了 - 取決於需要什麼類,您可以將其附加到您的模型或附加一個服務來爲您解決它。

假設它存在:

namespace MyRoot.General { 
    public interface IMyContext { 
     /// Some irrelevant stuff here 
    } 
} 

爲什麼不定義:

namespace MyRoot.General { 
    public interface IMyOtherThing { 
     /// Some new stuff here 
    } 
} 

,並實現它MyRoot.General.Model內:

namespace MyRoot.General.Model { 
    public class MyOtherThing : MyRoot.General.IMyOtherThing { 
     /// Some new stuff here 
    } 
} 
,然後圍繞它傳遞使用IMyContext上的新屬性

,然後添加一個新的接口,IMyContextEx:

namespace MyRoot.General { 
    public interface IMyContextEx : IMyContext { 
     IMyOtherThing MyOtherThing { get; set; } 
    } 
} 

最後,在需要的地方,以獲得新的屬性落實實現IMyContext同一類IMyContextEx,和演員。

+0

MyApp已經在使用IMyContext。所以,如果我創建一個IMyContextTwo ....會有很多重構。也許我沒有跟着。 – 4thSpace

+0

查看編輯我的意思 –

+0

您說的部分「,然後在IMyContext上使用新屬性傳遞它」將會對現有應用程序造成很大打擊。 – 4thSpace

1

你需要想想Adapter Pattern ...

你做的是類似如下:

public interface IMyAdapter : IMyContext 
{ 
    // additional contract requirements 
    string MyProperty { get; } 
} 

...然後...

public class MyAdapter : IMyAdapter 
{ 
    // fulfill contract 
} 

完成後,您將對此特定的適配器有新的要求。當該類型繼承以適應您的工作流程時,它必須遵循這兩個合同。如果你正在創造類似的東西:

IMyAdapter adapter = new MyAdapter(); 

...我想你會想隱式實施IMyAdapter,所以你可以參考IMyContext方法。

0

要包含在IMyContext上的屬性需要是抽象類型,也許是另一個接口。

MyRoot.General.Model程序集可以包含此接口的實現,或者甚至可以包含整個IMyContext接口本身的實現。

你的問題沒有真正提到你的IMyContext接口的具體實現。 MyRoot.General.MyApp可以在沒有MyRoot.General 的情況下實例化具體實現。

+0

IMyContext的具體實現在MyRoot.General中。 – 4thSpace