【问题标题】:Dependency Injection with Multiple Interfaces具有多个接口的依赖注入
【发布时间】:2014-10-06 06:38:56
【问题描述】:

我只是在学习接口隔离原则。但是在学习之后,我对示例中的场景感到困惑。

这个概念是将接口分离成简单的接口。这很好,但我的问题是层次模型与否?

以我在书中学习的例子为例。

我有一个具有以下属性的产品接口

public interface IProduct
{
decimal Price { get; set; }
decimal WeightInKg { get; set; }
int Stock { get; set; }
int Certification { get; set; }
int RunningTime { get; set; }
}

我只是通过界面中的一个类实现来简化

public class DVD : IProduct
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
public int Certification { get; set; }
public int RunningTime { get; set; }
}

问题是当应用于没有相关属性的其他类别时。为 TShirt 创建类时,不需要 Certification 和 RunningTime。所以按照接口分离原则,接口分离如下

创建一个新界面,将电影相关属性移动到这个界面,如下所示

public interface IMovie
{
int Certification { get; set; }
int RunningTime { get; set; }
}

所以 IProduct 没有这些属性和下面的实现

public class TShirt : IProduct
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
}

public class DVD : IProduct, IMovie
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
public int Certification { get; set; }
public int RunningTime { get; set; }
}

从概念上讲,我对此表示满意。但是,如果这与这样的真实方法实现有关。当我使用依赖注入时,我使用哪个接口作为 DVD 类的类型。

我很困惑还是我错过了什么?如果我应用继承逻辑,我们可以使用较低级别的接口,因此基接口也被继承。但是如果我这样使用怎么能实现呢?

【问题讨论】:

  • 接口隔离原则是将接口应用于服务,而不是实体。在您的情况下,您实际上将接口用作基本类型,因为DVDProduct。这里不可能应用接口隔离原则。

标签: c# interface dependency-injection


【解决方案1】:

如果您知道任何电影总是也将成为产品,那么您可以像这样定义您的接口,其中IMovie 扩展IProduct

public interface IProduct
{
    decimal Price { get; set; }
    decimal WeightInKg { get; set; }
    int Stock { get; set; }
}

public interface IMovie : IProduct
{
    int Certification { get; set; }
    int RunningTime { get; set; }
}

那么你的DVD 类就实现了IMovie 接口:

public class DVD : IMovie
{
    public decimal Price { get; set; }
    public decimal WeightInKg { get; set; }
    public int Stock { get; set; }
    public int Certification { get; set; }
    public int RunningTime { get; set; }
}

使用你的另一个例子,也许你的TShirt 实现了一个IClothing 接口,这也是一个产品:

public class IClothing : IProduct
{
    int Size { get; set; }
    Color Color { get; set; }
}

public class TShirt : IClothing
{
    public decimal Price { get; set; }
    public decimal WeightInKg { get; set; }
    public int Stock { get; set; }
    public int Size { get; set; }
    public Color Color { get; set; }
}

现在,当您注入依赖项时,您可以请求 IMovieIClothing 的实例。

【讨论】:

  • 很好,我也这么认为,但是 scneario 会造成混乱,所以继承就像这样 scnarios 很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 2013-04-11
  • 1970-01-01
  • 2023-04-06
  • 2017-06-10
  • 2010-12-16
相关资源
最近更新 更多