我有一个结构为服务层的应用程序,它使用存储库层进行持久化。
我正在尝试创建通用控制器类以重用共享行为,但是在尝试设置通用参数时遇到了麻烦。如下代码:

public class BusinessEntity
{ }

public class Person : BusinessEntity
{ }

public interface IRepository<T> where T : BusinessEntity
{ }

public interface IService<T, R>
    where T : BusinessEntity
    where R : IRepository<T>
{ }

public partial interface IPersonRepository : IRepository<Person>
{ }

public interface IPersonService : IService<Person, IPersonRepository>
{ }

public abstract class BaseController<X, Y>
    where X : BusinessEntity
    where Y : IService<X, IRepository<X>>
{ }

public class PersonController : BaseController<Person, IPersonService>
{ }


编译失败

类型ConsoleApplication.IPersonService不能用作通用类型或方法Y中的类型参数ConsoleApplication.BaseController<X,Y>。没有从ConsoleApplication.IPersonServiceConsoleApplication.IService<ConsoleApplication.Person,ConsoleApplication.IRepository<ConsoleApplication.Person>>的隐式引用转换

这有效

public interface IPersonService : IService<Person, IRepository<Person>>


但我丢失了自定义存储库

有一种方法可以使编译器意识到IPersonRepositoryIRepository<Person>吗?

最佳答案

public class BusinessEntity
{ }

public class Person : BusinessEntity
{ }

public interface IRepository<T> where T : BusinessEntity
{ }

public interface IService<T, R>
    where T : BusinessEntity
    where R : IRepository<T>
{ }

public partial interface IPersonRepository : IRepository<Person>
{ }

public interface IPersonService : IService<Person, IPersonRepository>
{ }

public abstract class BaseController<X, Y, Z>
    where X : BusinessEntity
    where Y : IService<X, Z>
    where Z : IRepository<X>
{ }

public class PersonController : BaseController<Person, IPersonService, IPersonRepository>
{ }


要发表您的评论:


  IPersonService可以扩展基本服务类以添加自定义功能,例如FindPersonsUnderAge()。为此,它需要一个自定义存储库。实际上,LINQ避免了很多自定义存储库代码,但有时是必需的。


如果不要求存储库类型为类型参数,IPersonService不能这样做吗?例如:

public interface IService<T> where T : BusinessEntity { }

public interface IPersonService : IService<Person>
{
    IEnumerable<Person> FindPersonsByAge(double minAge, double maxAge);
}

public class Service<T, R> : IService<T>
    where T : BusinessEntity
    where R : IRepository<T>
{ }

public class PersonService : Service<Person, IPersonRepository>, IPersonService
{ }

10-04 16:39