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;
}
}
My problem is:
- IDBContext is a registered dependency within Ninject. Accessing the concrete type directly by instantiating it would be a no-no.
- I must somehow get that dependency injected into this class or somehow access the dependency through some other class that already has the dependency resolved.
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)
- Implement the service locator pattern to just simply resolve my IDBContext dependency from within the ViewModel.
- Resolve the IDBContext within my controller and pass it into my ViewModel upon manual construction of the ViewMode i.e.
new CreateGetIncidentViewModel(dbContext);
- This doesn't solve the problem of the view model being hydrated by MVC though when the model is being posted to an action
Suggestions?