Reputation: 14145
let's say that I have some IBookRepository. And besides ravendb I want to add SqlServer implementation of IBookRepository called SQLServerRepository.
What is the proper way to create implemenation of this interface having db context in mind. Should I pass dbcontext as parameter inside SQLServerRepository constructor and populate class member dbcontext to work with db?
public class SQLServerBookRepository : IBookRepository
{
private MyDBContext _db;
public SQLServerRepository(MyDBContext db)
{
_db = db;
}
public void AddBook(Book b){
// adding book to context
_db.SaveChanges();
}
}
I'm asking is this proper way? Is there are better way? Where should I store dbcontext in the same layer with repository, dao layer, how would you do it?
Upvotes: 0
Views: 109
Reputation: 13224
Yes, the proper way is not to do this. The "Repository" pattern as an additional layer over a library that already abstracts the database is an anti-pattern.
Furthermore, the paradigms of a document database like RavenDB and a relational database are very different. You would not solve / model your solutions in the same way.
Refer to this blog post "RavenDB and the Repository pattern", by a user of RavenDB who had similar intentions as you expressed, summarizing a discussion between himself and Ayende Rahien (aka Oren Eini), the creator of RavenDB.
Regarding your follow up "what if" question, related to creating a repository for EF. My advice would be the same: don't.
Entity Framework is already abstracting the database for you. It provides its own versions of a "Repository" as a DbSet
and a "unit of work" as the DbContext
. Don't put another abstraction layer over it that will always be:
Upvotes: 1
Reputation: 14713
I generally manage DataContext lifetime outside of my repositories. I use my IoC tool (usually structuremap) to scope context to HttpContext. Then I simply inject an instance of my DataContext into my repositories.
Upvotes: 1