I'm experiencing some problem with the context using EF5. I'm still studying the problem, but I was thinking is would be a good idea to implement my DataContext class with the singleton pattern, in order to have the same object used by different entity repository. Is a suicide or does it make sense? Another idea is implement a ContextManager like here: http://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En (but I'm still checking his code and I don't really understand it in depth yet).
What do you think?
--EDIT--
In a web application, I'm implementing a repository for each entity I have to manage
public DataContext : DbContext
{
//...
}
Solution 1: fine, but if I would need to make several actions in one call, i.e. an insert and a delete, I'll make two calls to db, I think.
public Entity1Repository
{
public void Add(Entity1 entity)
{
using(DataContext context = new DataContext())
{
context.Entity1.Add(entity);
context.SaveChanges();
}
}
public void Delete(Entity1 entity)
{
using(DataContext context = new DataContext())
{
context.Entity1.Remove(entity);
context.SaveChanges();
}
}
}
Solution 2: in this case I think I'll have just one call to db, but I need to remember to call the Dispose()
public Entity1Repository
{
private DataContext context;
public void Add(Entity1 entity)
{
context.Entity1.Add(entity);
}
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
Which is the best implementation? (If I understood correctly, singleton is not a good one)