I'm using Ninject for dependency injecting in an ASP.Net MVC application (This is my first project using Ninject or DI at all for that matter).
I'm opting to using the Model-View-ViewModel pattern. The view model will provide all my properties I'll bind to my actual view, but also need to access the database for things such as lists of data. Eg:
public class CreateGetIncidentViewModel
{
private IDBContext _dbContext = null;
[Required]
public EmployeeType EmployeeType { get; set; }
[Required]
[StringLength(50)]
public string Department { get; set; }
/
public IEnumerable<SelectListItem> GetEmployeeTypeSelectList()
{
// Simplified for brevity
var employeeTypes = _dbContext.EmployeTypes.Where().... // Go select the employee types
var employeeTypeSelectList = new List<SelectListItem>();
foreach(var employeeType in employeeTypes){
employeeTypeSelectList.Add(new SelectListItem(){
// Set select list properties
});
}
return employeeTypeSelectList;
}
}
Given that my ViewModel is often hydrated by ASP.Net MVC automatically through model binding, how do I get my dependency into my ViewModel?
There are multiple ways which I've through about but they all seem dirty. I COULD (but don't want to)
new CreateGetIncidentViewModel(dbContext);
Suggestions?
Given that my ViewModel is often hydrated by ASP.Net MVC automatically through model binding, how do I get my dependency into my ViewModel?
You could write a custom model binder that will inject the dependency into the view model constructor.
This being said, using the MVVM pattern in ASP.NET MVC IMHO is wrong approach from the beginning and if you go that way you must be prepared for lots of suffering. Are you ready for that?
If not, here's what I would recommend you:
Controller -> Domain model -> View model -> View
In this pattern you have the controller knowing about the repository (DbContext
- being injected automatically into it by your DI framework).
Flow 1:
Flow 2:
In this examples the view model doesn't know anything about any repository or data access or DbContexts. The view model is the representation of the view. The mapping between the domain model and the view is a responsibility of the controller (which could be delegated to a mapping layer). Personally I use AutoMapper
to perform the mapping between my domain models and view models.
In case you wish to go the Custom Model Binder route that Darin mentioned, check this out: https://stackoverflow.com/a/24166483/71906
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With