I would recommend you using ViewModels and passing only view models to the views. This way you don't have to worry about disposing. Also abstract and separate your data access into a repository:
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);
}
}
Now the disposal of the repository is a concern of its creator which if you follow good practices is a Dependency Injection framework. In order to instantiate your controller you need an instance of a repository to be passed into the constructor and most good DI frameworks will automatically dispose objects that implement IDisposable
.