Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何为我的服务层设计更灵活的结构_C#_Oop_Solid Principles - Fatal编程技术网

C# 如何为我的服务层设计更灵活的结构

C# 如何为我的服务层设计更灵活的结构,c#,oop,solid-principles,C#,Oop,Solid Principles,谈到接口隔离原则,我正在评估我在服务层中经常使用的接口的设计: public interface ICrudService<D> { IList<D> GetAll(); bool Exists(int id); D GetById(int id); D NewInstance(); D Create(D dto); D Update(D dto); void Delete(int id); } 公共接

谈到接口隔离原则,我正在评估我在服务层中经常使用的接口的设计:

public interface ICrudService<D>
{
    IList<D> GetAll();

    bool Exists(int id);

    D GetById(int id);

    D NewInstance();

    D Create(D dto);

    D Update(D dto);

    void Delete(int id);
}
公共接口ICrudService
{
IList GetAll();
bool存在(int-id);
D GetById(int-id);
D NewInstance();
D创建(D dto);
D更新(D dto);
无效删除(int-id);
}
我通常使用这个接口的抽象实现,并从抽象类继承我的具体服务

但很明显,我并不总是需要在我的服务类中使用所有这些方法,所以我希望使这种结构更加灵活

一个选项是通过以下方式拆分接口(和抽象类):

public interface IGetAllService<D>
{
    IList<D> GetAll();
}

public interface IExistsService<D>
{
    bool Exists(int id);
}

// etc.
公共接口服务
{
IList GetAll();
}
公共接口IExistService
{
bool存在(int-id);
}
//等等。
然后在我的具体类中实现所需的方法:

public class ConcreteService : IGetAllService<ConcreteEntity>, IExistsService<ConcreteEntity>
{
    // implemented methods
}
公共类具体服务:IGetAllService、IExistService
{
//实施方法
}
但这是好的设计吗


有没有更好的方法使我的应用程序结构更加灵活和可重用?

看来您是从抽象类派生来继承默认实现的。不要为了代码重用而滥用继承。继承是为了创建可替换性。自己创建一些助手方法。这样,您就可以创建想要公开的方法。

我认为更好。我唯一的建议是不要将自己限制为整数键-使用另一个通用参数来指示键类型:
igetbydservice{..}
@Jamiec:code review用于现有的、完整的工作代码。设计问题在imho更为常见。@cosmo0足够公平,我在两个TBH上都不太活跃。这是或多或少的工作代码。您使用该接口的目的是什么?我明白了,你能不能简单地没有一个接口,依赖于惯例。涉及到一个抽象类?不要为了代码重用而滥用继承。继承是为了创建可替换性。自己创建一些助手方法。这样,您就可以创建想要公开的方法。