我不确定我想做的事情是否可行,因为我在谷歌上没有找到任何东西,经过大约 30 分钟的密集搜索后,我决定直接询问。
我已经为我的存储库定义了一个简单的接口(interface)
public interface IRepository<TEntity> : IDisposable
{
TEntity GetById(object id);
List<TEntity> GetAll();
}
现在我想实现我的第一个存储库,它是这样工作的
public class ContentRepository : IRepository<ContentPages>
{
private readonly Context _db = new Context();
public ContentPages GetById(object id)
{
var result = _db.ContentPages.Find(id);
return result;
}
public List<ContentPages> GetAll()
{
return _db.ContentPages.ToList();
}
public void Dispose()
{
_db.Dispose();
}
}
这工作正常,但是当我将我的存储库注入(inject)我的 mvc Controller 时,它需要一个 IRepository<ContentPages>
作为参数类型,我只希望它采用 IRepository
.
我试图像这样将泛型类型移动到函数本身
public interface IRepository : IDisposable
{
TEntity GetById<TEntity>(object id);
List<TEntity> GetAll<TEntity>();
}
}
当我这样做时,我不知道如何定义我的泛型类型 TEntity
在实现中
所以总而言之,我希望在不指定类型的情况下使用接口(interface),这样它就可以像这样从实际对象中获取类型
public constructor1(IRepository ContentRepository){}
下一个 Controller 得到这个构造函数
public constructor2(IRepository BlogRepository){}
等等
我希望我能详细描述我的问题,让你们能够理解:)
最佳答案
在 IRepository
类的具体实现中,您可以按如下方式定义 TEntity 的类型。
public TEntity GetById<TEntity>(object id) where TEntity:class
{
// Implimetation
}
但在这里根据存储库模式更好地使用如下。
public interface IRepository<TEntity>: IDisposable where TEntity : class
关于c# - 在存储库中实现通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19881966/