我會推薦你使用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
的對象。