Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a knot with Generics

Tags:

c#

generics

I have the following domain object:

public class DomainObject<T,TRepo> 
  where T : DomainObject<T>
  where TRepo : IRepository<T>
{
      public static TRepo Repository { get;private set; }
}

A repository interface:

public interface IRepository<T> //where T : DomainObject<T> // The catch 22
{
    void Save(T domainObject);
}

An implementation of the 2:

public class User : DomainObject<User,MyRepository>
{
    public string Name { get;private set;}
}

public class MyRepository : IRepository<User>
{
    public List<User> UsersWithNameBob()
    {

    }
}

So adding another method that isn't inside IRepository.

I want to enforce the repository as an IRepository while above it could be any type.

A small sidenote: I'm writing this for small systems with very few domain objects. I'm not looking to create anything that uses IoC, but rather something that is easy and simple to consume.

Thanks

like image 916
Arec Barrwin Avatar asked Oct 18 '25 23:10

Arec Barrwin


1 Answers

Not exactly sure what you want, but something like this compiles:

public class DomainObject<T, TRepo> 
     where T: DomainObject<T, TRepo> 
     where TRepo: IRepository<T, TRepo>
{
     public static TRepo Repository
     {
         get;
         private set; 
     }
}

public interface IRepository<T, TRepo>
     where T: DomainObject<T, TRepo>
     where TRepo: IRepository<T, TRepo>
{
     void Save(T domainObject);
}
like image 118
Lucero Avatar answered Oct 20 '25 13:10

Lucero