2011-08-24 70 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