I am fairly new to the MVP and the Entity Framework world so bear with me.
I currently have a View + Presenter combination, the view has two events Edit and Delete and the presenter just listens for these events. I also have a service object and repositories set up. The service layer takes some repository implementations which take an ObjectContext so the order of construction is (passing in the top object to the one below it:
ObjectContext
|
V
Repositries
|
V
Service Object
|
V
Presenter
Now the problem is that when I create object context at the top, It's alive for the whole time the presenter is alive meaning that Edit and Delete use the same context instance from the service.
So calling ServiceObject.Delete and ServiceObject.Edit use the same context which makes it hard to manage change tracking. From what I understand the context should really only be short lived and only for a unit of work, to me Edit and Delete are both different lots of work.
How do you do DI with the entity framework and still manage context life time?
I have seen people just new up the object context in side the repository, is this a good pattern.
Or should I do that in the service object, something like:
ServiceObject{
public void Edit(// some args) {
Using(var context = new MyObjectContext) {
var repo = new MyRepo(context);
var entity = repo.GetForID(12);
// Do some stuff for edit
context.SaveChanges();
}
}
}
But If I do it like that I am no longer passing my repository into the constructor of ServiceObject and not doing DI :(.
What can I do in this situation?
Does anyone know any open source projects that I can look at that may help me with this problem.
Thanks.