IoC服务的抽象类或接口 [英] Abstract class or Interface for IoC service?

查看:133
本文介绍了IoC服务的抽象类或接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用IoC在项目中提供仓库的具体实现。我读过的所有示例都使用接口作为服务的定义。但是,从Microsoft获取建议后,建议更喜欢通过接口进行抽象类

I am currently using IoC for providing concrete implemenations of repositories in a project. All of the examples that I have read use an interface as the definition of the service. However, having read recommendations from Microsoft it is recommended to prefer abstract classes over interfaces.

我发现这有助于模板模式,以减少重复。例如给出一个产品类与一个属性 IsActive 我可以使用一个接口的存储库,如:

I have found this useful in conjuntion with the template pattern to reduce repetition. For example give a Product class with a property IsActive I could use an interface for the repository such as:

interface IProductRepository
{
    IEnumerable<Product> Load();
}

如果一个常见的任务是加载活动产品,那么我需要做:

If a common task is to load active products then I would need to do:

IEnumerable<Product> activeProducts = repository.Load().Where(x => x.IsActive);

其中存储库是一个具体的实现。如果我使用抽象类,例如:

Where repository is a concrete implementation. If I used an abstract class such as:

abstract class ProductRepository
{
    protected abstract IEnumerable<Product> LoadCore();

    public IEnumerable<Product> Load()
    {
        return LoadCore().Where(x => x.IsActive);
    }
}

然后我可以使用

IEnumerable<Product> activeProducts = repository.Load();

所有用于加载产品信息的实现都在派生 ProductRepository 所以没有与持久层的耦合。如果发现有另一个常用的活动,那么这可以作为不可破坏的变化添加到基类中。这种更改无法使用接口进行。

All the implementation for loading the product information is within the contrete class that derives ProductRepository so there is no coupling to the persistance layer. If it is found that there is another commonly performed activity then this could be added to the base class as a non-breaking change which could not be done using an interface.

使用界面而不是抽象类有什么好处吗?我可以遇到什么潜在的缺点使用抽象类?

Is there any benefit to using an interface instead of an abstract class? What potential drawbacks to using abstract classes could I come across?

我正在使用Castle Windsor作为IoC控制器和.Net框架3.5。

I am using Castle Windsor as the IoC controller and .Net framework 3.5.

推荐答案

我不认为这个问题取决于IoC;大多数这些框架不在乎你使用哪种。

I don't think this question hinges on IoC; most of these frameworks don't care which you use.

通过抽象基类使用接口的最大问题是接口不能很好地版本化。

The big issue between using interfaces over abstract base classes is that interfaces cannot be versioned well.

由于这个原因,抽象基类通常是更好的选择。我不认为使用抽象基类没有任何缺点,除了获得支持问题,例如为什么我不能创建这种类型的实例?

Abstract base classes are usually the better choice because of this. I don't think there is any drawback to using an abstract base class, other than getting support questions like "why can't I create an instance of this type?"

这篇关于IoC服务的抽象类或接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆