Hi everyone,
I've been reading about a few design patters (that are part of DDD) to solve some of the issues I'm facing on my project. One of those patterns is the UnitOfWork pattern. So after reading a bunch of blogs about the subject, I noticed that the authors of the blogs give too much attention to something called
ObjectContext. Since I'm using the Entity Framework as my ORM, I believe the ObjectContext in my case is a class which inherits from DbContext (EF Code First CTP5).
Ok that's all fine but I still did not know why I should even care about this. So I started reading more about ObjectContext and apparently it could consume a lot of resources when it starts tracking multiple entities. Moreover, I read on a blog that when used in a web application (and not WinForms or WPF..etc) it should be attached to HttpContext.Current, otherwise it will cause some performance issues.
To wrap this up, I found out that among all the approaches that could be followed to manage the ObjectContext lifetime, the following two are my best options:
1. Use one context across all operations done by the repository instance (class level lifetime)
public class MyRepository : IDisposable {
ObjectContext _context;
public MyRepository(ObjectContext someContext) {
_context = someContext;
}
public IQueryable<Entity> GetAll() {
return _context.Entities;
}
//implement the IDisposable interface
}
2. Create a new context inside each method (function level). In this case I should make sure the context class itself implements IDisposable.
public class MyRepository {
public IQueryable<Entity> GetAll() {
using(var context = new EntitiesContext) {
return context.Entities;
}
}
public Entity GetEntityById(int id) {
using(var context = new EntitiesContext) {
return context.FirstOrDefault(e => e.EntityID.Equals(id));
}
}
//other methods follow the same pattern
}
Questions:
1. Did I get the concept of a context (ObjectContext) right?
2. Which one of the above approaches is better, performance wise? Is there another alternative that is better than both?
3. How do I attach the ObjectContext to the HttpContext.Current? Where exactly does that happen (which layer I mean... Data layer, business/service, presentation)?