这可能是以前问过的,但我无法解决。也许如果我能把标题弄对,我就可以用谷歌搜索它。
我有这个通用的存储库接口(interface):
public interface IRepository<TEntity>
{
TEntity Resolve<TEntity>(); // dummy function, just to get the idea
}
我还有一个通用工作单元,它能够解析通用存储库:
public interface IUnitOfWork
{
IRepository<TEntity> GetGenericRepository<TEntity>() where TEntity : class;
}
到目前为止一切顺利。
但是随着现实生活的继续,我想创建一个具有一些特定功能的自定义存储库。所以我在想:继承;像这样:
public class SpecialRepository : IRepository<SomeEntityType>
{
public void SomeSpecialFunction() { };
}
显然,这种类型不能用 GetGenericRepository 解析方法所以我想:让我们添加一个额外的方法到 IUnitOfWork接口(interface):
public interface IUnitOfWork
{
//same old get generic repository
IRepository<TEntity> GetGenericRepository<TEntity>() where TEntity : class;
//the newly added.
T GetInheretedRepository<T>() where T : class;
}
我希望能够使用特殊存储库调用工作单元,如下所示:
public test()
{
IUnitOfWork uow = new UnitOfWork();
//I want to make this call with a constraint on TemplateRepo
//to enforce it's type: IRepository<T> (which TemplateRepo is)
var y = uow.GetInheretedRepository<TemplateRepo>();
}
问题是:我如何限制类型 T在 T GetInheretedRepository<T>() where T : class;类型:IRepository<TEntity> ?
我试过这个:
public interface IUnitOfWork
{
//the newly added.
//error: Only class or interface could be specified as constraint
T GetInheretedRepository<T>() where T : class, IRepository; }
和
public interface IUnitOfWork
{
//the newly added.
//error: type argument missing
T GetInheretedRepository<T>() where T : class, IRepository<>;
}
那行不通。
我可以放弃约束作为快速修复或者创建一个继承的工作单元,但是随后;问题仍然存在。
请您参考如下方法:
这样做的方法是添加第二个泛型类型参数,如下所示:
TRepository GetInheretedRepository<TRepository, TEntity>()
where TRepository : IRepository<TEntity>
where TEntity : class;
此处您提供存储库类型和实体类型。这样 C# 编译器可以检查类型是否匹配。调用方法如下:
var rep = uow.GetInheretedRepository<SpecialRepository, SomeEntityType>();
rep.SomeSpecialFunction();
这显然很糟糕,因为您必须指定这两种类型。但更重要的是,这很糟糕,因为您必须指定具体类型,从而使您的代码依赖于具体类型;违反了 Dependency Inversion Principle 。
我真的很想建议远离依赖于具体类型的设计,或者更好的是,远离在特定存储库类上有许多方法的设计,因为这违反了 SRP , OCP 和 ISP,这可能会导致以后的维护问题。
因此,请查看 this article 中描述的应用程序设计。
