2014-02-05 30 views
0

我正在使用与the example Microsoft provides几乎相同的工作单元/通用存储库模式,并且它工作得很好。但是,最近出现了一些仅适用于特定类型存储库的方法。将非泛型方法添加到泛型类

例如,假设我有两个对应于数据库表的类:PeopleSpaceships

unitofwork.PeopleRepository<Person>unitofwork.SpaceshipsRepository<Spaceship>。虽然这两个库有方法,我在

public class Repository<TEntity> where TEntity : class, IEntity 

定义,如果我想要一些Person特异性方法可用上unitofwork.People?这可能吗?

+0

这就是使用通用一致通用类的想法失败的地方。分开您的疑虑并为您的存储库单独创建查询类。 – trailmax

回答

2

您可以使Repository<T>为抽象类。然后,每个实体必须有自己的实现:

abstract class RepositoryBase<TEntity> where TEntity : class, IEntity { 
    void Add(TEntity entity); 
    ... 
} 

class PeopleRepository : RepositoryBase<Person> { 
    string GetPersonName(); 
} 

class SpaceshipRepository : RepositoryBase<Spaceship> { 
    void Fly(); 
} 

你会然后实现类为:

unitofwork.People = new PeopleRepository(); 
unitofwork.People.Add(new Person()); // Can access the base class 
Console.WriteLine(unitofwork.People.GetPersonName()); // People-specific methods 
unitofwork.Spaceships = new SpaceshipRepository(); 

如果你希望能够初始化基础信息库的一个实例,有没有必要将其标记为abstract

class Repository<TEntity> where TEntity : class, IEntity { 
    void Add(TEntity entity); 
} 

class PeopleRepository : Repository<Person> { 
    string GetPersonName(); 
} 

如果你想从提供自己的我停止PeopleRepository那么你可以使用sealed修饰符:

class Repository<TEntity> where TEntity : class, IEntity { 
    sealed protected void Add(TEntity entity); 
} 
+0

是的!我知道有这样的事情。只是不记得它叫什么。抽象。谢谢! – Andrew

+0

实际上,我不想抽象,因为我没有提到还有其他类型,我不需要特定的方法,并且想要实例化通用存储库。我所需要的只是继承这个班级,事后看来这显得非常显而易见。我正在努力克服它。 – Andrew

+0

我认为这意味着您的答案中的“可选”一词在技术上是不正确的。它看起来像每个实体*必须*有自己的实现,如果基类是'抽象'。 – Andrew