我想使用存储库模式(我知道我可以使用工作单元模式,但我想在这里使用存储库模式)。因此,在每个存储库类中,我都有对特定表的查询,例如:
public class NotesRepository : INotesRepository, IDisposable
{
private DatabaseContext context;
public NotesRepository(DatabaseContext context)
{
this.context = context;
}
public IQueryable<Notes> GetAllNotes()
{
return (from x in context.Notes
select x);
}
}
还有另一个存储库示例:
public class CommentsRepository : ICommentsRepository, IDisposable
{
private DatabaseContext context;
public CommentsRepository(DatabaseContext context)
{
this.context = context;
}
public IQueryable<Comments> GetAllComments()
{
return (from x in context.Comments
select x);
}
}
现在我想在一个控制器中使用这两个存储库。因此,使用存储库模式,我在控制器构造函数中初始化数据库连接并将其传递给每个存储库,对吗?例如:
public class HomeController : Controller
{
private INotesRepository NotesRepository;
private ICommentsRepository CommentsRepository;
public HomeController()
{
DatabaseContext db = new DatabaseContext();
this.NotesRepository = new NotesRepository(db);
this.CommentsRepository = new CommentsRepository(db);
}
// ........
}