Providing an IDisposable call to objects created in the controller and submitted for viewing

I always knew that all good programmers call Dispose on any object that implements IDisposable, in case the ObjectContext class is in EF.

I am new to asp.net mvc, so this might be a noob question, but here goes ...

    public ActionResult Index()
    {
        using (var db = new MyObjectContext())
        {
            return View(db.People);
        }
    }

If I run this code, I get an error (ObjectDisposedException) because the ObjectContext was deleted before the View took action on the data. Is there a different approach here? How can I ensure that my objects are deleted as soon as possible?

+3
source share
2 answers

Cancel the Controller.Dispose () method and place your object there:

private IDisposable _objectToDispose;

public ActionResult Index() {
  var db = new MyObjectContext();
  _objectToDispose = db;
  return View(db.People);  
}

protected override void Dispose(bool disposing) {
  if (disposing && _objectToDispose != null) {
    _objectToDispose.Dispose();
  }
  base.Dispose(disposing);
}

MVC Controller.Dispose() .

+8

ViewModels . , . :

public interface IPersonRepository
{
    IEnumerable<Person> GetPeople();
}

public class PersonRepositorySql : IPersonRepository, IDisposable
{
    private MyObjectContext _db = new MyObjectContext();

    public IEnumerable<Person> GetPeople()
    {
        return _db.People;
    }

    public void Dispose()
    {
        _db.Dispose();       
    }
}

public class HomeController : Controller
{
    private readonly IPersonRepository _repository;

    public HomeController(IPersonRepository repository) 
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        IEnumerable<Person> people = _repository.GetPeople();

        // Using AutoMapper here but could be anything:
        IEnumerable<PersonViewModel> peopleViewModel = Mapper
            .Map<Person, PersonViewModel>(people);

        return View(peopleViewModel);
    }
}

, , , . , , , DI , IDisposable.

+2

Source: https://habr.com/ru/post/1763136/


All Articles