I am about to start a small/medium sized project. I am by no means a software architect. But I tend to question every move I make at times, since I want to do things correct.
I found a way to implement a simple repository, and I wanted to know if this is a "correct" way of doing it. I came to this solution, since I know what is going on, and not taking in something to complex before I have the knowledge.
Unit of work
Where I make sure I to keep all my repositories under the same dbcontext. In my UOW I can access all repos when calling it from the controller.
public class UnitOfWork : IDisposable
{
private ContactRepository _contactRepo;
private ApplicationDbContext _entities;
public UnitOfWork(ApplicationDbContext entities)
{
_entities = entities;
}
public ContactRepository ContactRepo
{
get
{
if (_contactRepo == null)
{
_contactRepo = new ContactRepository(_entities);
}
return _contactRepo;
}
}
public void Save()
{
_entities.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
ContactRepository
This is a short example of a repository, where it receives the dbcontext and uses it to grab whatever data I want.
public class ContactRepository
{
private ApplicationDbContext _entities;
public ContactRepository(ApplicationDbContext entities)
{
_entities = entities;
}
public IEnumerable<Contact> GetAll()
{
return _entities.Contacts;
}
}
Controller
Short example of controller
public class ContactController : Controller
{
UnitOfWork uow = new UnitOfWork(new ApplicationDbContext());
public ActionResult Index()
{
var contacts = uow.ContactRepo.GetAll();
return View(contacts);
}
protected override void Dispose(bool disposing)
{
uow.Dispose();
base.Dispose(disposing);
}
}
In this way I will have access to all my repositories under the same dbcontext which I was aiming for.
I know things can be done smarter/different. With for example a extendable generic repo. But in this case I am aiming for something simple and understandable. But still don't want to make a huge mistake, if there is a major flaw.
Do you see any major flaws with this way of handling data through entity framework?