zosim
zosim

Reputation: 2979

How to dispose objects correctly (ASP.NET MVC + Entity Framework)

I would like to know how to dispose objects correctly in the following situation. This is a ASP.NET MVC controller action. There is a repository which implements IDisposable. Attachment entity contains related entity Task. When I click on the attachment detail, it is displayed correctly. But when I click on the task, then the following exception is threw "The ObjectContext instance has been disposed...". I understand, that when the view is rendered it is disposed and the ObjectContext is closed.

public ActionResult Detail(Guid id)
{
    Attachment attachment = null; 
    using (var attachmentRepository = IoC.Resolve<AttachmentRepository>())
    {
        attachment = attachmentRepository.SelectByKey(id);
        return View("Detail", attachment);            
    }          
}    

My question is what is best practise in this scenario?

Is this a good solution? When will be the ObjectContext disposed in this situation? When the user go to another view? Or when the garbage collector will be executed?

public ActionResult Detail(Guid id)
{
    Attachment attachment = null; 
    var attachmentRepository = IoC.Resolve<AttachmentRepository>();

    attachment = attachmentRepository.SelectByKey(id);
    return View("Detail", attachment);                              
}    

thanks

Upvotes: 2

Views: 891

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160902

Your Task entity was not retrieved as part of your original query, so EF is trying to lazy load it which fails since the context has been disposed. You should use an Include() query to retrieve the Task entity as part of your original query to avoid having to go back to the database later on (which also would mean that you would have to keep the context alive).

Also you are not really doing IoC here, you are using the Service locator (Anti-) pattern. You should have your IoC container pass in your repository as a constructor dependency to your controller. The IoC container in turn should be responsible for the lifetime management of your repository instances.

Upvotes: 2

Related Questions