如何解决通过System.Reflection获取类型:尝试投射它们时出错
我尝试通过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 举报,一经查实,本站将立刻删除。