我有一堆存储库类,它们看起来都有点像下面的。请注意,我省略了某些方法;我只是想让您尝一尝。
public class SuggestionRepository : ISuggestionRepository
{
private IUnitOfWork _unitOfWork;
public SuggestionRepository(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public Suggestion Load(int id)
{
Suggestion suggestion;
suggestion = _unitOfWork.Load<Suggestion>(id);
return suggestion;
}
public IQueryable<Suggestion> All
{
get { return _unitOfWork.GetList<Suggestion>(); }
}
}
您可以想象我的存储库之间重复代码的数量。
我想创建一个Repository<T>类,它由我的存储库扩展,这样我就不必为每个存储库编写样板代码了。此类可能类似于以下内容:
internal class Repository<T> where T : Entity
{
private IUnitOfWork _unitOfWork;
internal Repository<T>(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public T Load(int id)
{
T t;
t = _unitOfWork.Load<T>(id);
return t;
}
public IQueryable<T> All
{
get { return _unitOfWork.GetList<T>(); }
}
}
但是visualstudio并没有表现出任何爱。它在参数列表括号中表示“unexpected token”,表示它不能在静态上下文中访问非静态字段unitOfWork,并假装它不知道参数unitOfWork是什么。