Implicit en conversions to c # generic classes
I have an application that is structured as a service layer that uses the repository layer to persist. I'm trying to create a generic controller class to reuse shared behavior, but I'm having trouble trying to set the generic options. The following code:
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>
{ }
cannot compile with
A type ConsoleApplication.IPersonService
cannot be used as a type parameter Y
in a generic type or method ConsoleApplication.BaseController<X,Y>
. There is no implicit conversion of references from ConsoleApplication.IPersonService
toConsoleApplication.IService<ConsoleApplication.Person,ConsoleApplication.IRepository<ConsoleApplication.Person>>
it works
public interface IPersonService : IService<Person, IRepository<Person>>
but I am losing my custom repository
Is there a way to make the compiler implemented IPersonRepository
- is this IRepository<Person>
?
source to share
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>
{ }
To submit your comment:
IPersonService can extend the base service class to add custom tools such as FindPersonsUnderAge (). This requires a dedicated repository. In fact, LINQ avoids a lot of custom repository codes, but sometimes they are required.
Can't IPersonService do this without requiring the repository type to be a type parameter? For example:
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
{ }
source to share