问题描述
我尝试通过Reflection在我的项目中获取数据库存储库,并将它们存储在列表中,如下面的代码所示。
所有存储库都实现IRepository<TEntity>
接口,而TEntity必须实现IObjectWithId
接口。
在下面的示例中:当我尝试在foreach循环中创建存储库的实例并将其存储在列表中时,我收到一条错误消息,提示无法将ExampleRepository
强制转换为IRepository<IObjectWithId>
public void GetRepositories(Entities context)
{
this.ProcessRepositories = new List<IRepository<IObjectWithId>>();
Assembly assembly = Assembly.GetAssembly(this.GetType());
var types = assembly.GetTypes().ToList();
types = types.Where(t => t.Name.Contains("Repository")).ToList();
foreach (var type in types)
{
this.ProcessRepositories.Add((IRepository<IObjectWithId>)Activator.CreateInstance(type,context)); //Error at this point
}
}
//Interface for Repositories
public interface IRepository<TEntity> where TEntity : IObjectWithId
{
IEnumerable<TEntity> Get(Expression<Func<TEntity,bool>> filter = null,Func<IQueryable<TEntity>,IOrderedQueryable<TEntity>> orderBy = null,string includeProperties = "");
}
//Example Repository
public class ExampleRepository : BaseRepository<ExampleEntity>,IRepository<ExampleEntity>
{
public ExampleRepository (Entities context) : base(context)
{
}
}
//Example Database Entity
public class ExampleEntity : IObjectWithId
{
}
public class BaseRepository<TEntity> where TEntity : class,IObjectWithId
{
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity,string includeProperties = "")
{
try
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
catch(Exception e)
{
return new List<TEntity>();
}
}
}
有人可以帮我弄清楚我的代码有什么问题吗?如果删除通用类型<TEntity>
,它将按预期工作。所以这有什么问题,但我真的不明白为什么。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)