I have a data access library that has a few classes that all implement the same interface, which has a generic type parameter:
public interface IGetByCommonStringRepository<TEntity>
{
TEntity GetByCommonStringColumn(string commonString);
}
public class Repository1<Entity1> : IGetByCommonStringRepository<Entity1>
{
public Entity1 GetByCommonStringColumn(string commonString)
{
//do stuff to get the entity
}
}
public class Repository2<Entity2> : IGetByCommonStringRepository<Entity2>
//...and so on
Rather than forcing consumers of this library to instantiate one of the four repository classes separately for each <TEntity>
, I am hoping that there's some way that I can create a static method in a "helper/utility" class in the same assembly that will be able to discern which implementation to instantiate, create an instance, and execute the GetByCommonStringColumn
method. Something like...
public static TEntity GetEntityByCommonStringColumn(string commonString) where TEntity : class
{
IGetByCommonStringRepository<TEntity> repository =
DoMagicalReflectionToFindClassImplementingIGetByCommonString(typeof(TEntity));
//I know that there would have to an Activator.CreateInstance()
//or something here as well.
return repository.GetByCommonStringColumn(commonString) as TEntity;
}
Is anything like this possible?
Thanks in advance.