I have the following hierarchy of interfaces:
public interface IEntity { object Key; }
public interface IEntity<TKey> { TKey TypedKey; }
In my repository layer, I have a GetOne method currently defined as such:
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : IEntity
{
public TEntity GetOne(object key) { ... }
}
I would like to constrain the argument on the repository to the TKey type specified by the generic interface of the entity. The obvious solution would be:
public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
where TEntity : IEntity<TKey>
{
public TEntity GetOne(TKey key) { ... }
}
This works, but requires me to specify the TKey explicitly when creating a repository, or injecting it via the interface. What I would like to do is something like this (the following code will not work, though):
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : IEntity
{
public TEntity GetOne<TKey>(TKey key) where TEntity : IEntity<TKey> { ... }
}
Is it at all possible to constrain TKey to be the generic parameter of IEntity without specifying it on the class? If so, how would I do that?
public class Repository<TEntity> : IRepository<TEntity> where TEntity : IEntity<string>? - ColinMGetOne(string)then. The point is that the key might be an int, a string, a long, or even a composite object. - Maciej Stachowski