我有一个数据访问库,它有几个类都实现相同的接口,这些类有一个通用类型参数:
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
而不是强迫这个库的使用者为每个库分别实例化四个存储库类中的一个
<TEntity>
,我希望有某种方法可以在同一程序集中的“helper/utility”类中创建静态方法,该方法能够识别要实例化、创建实例和执行
GetByCommonStringColumn
方法。有点像…
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;
}
这样的事有可能吗?
事先谢谢。