How to achieve dependency injection on ViewModel classes?
I have a view model class which has a method that does a calculation based on the period of time between a date on the viewmodel with the current time using DateTime.Now.
I want to be able to Unit Test t开发者_高级运维he method so I'm using a time service which can be stubbed in my tests. However, the dependency needs to be injected into the viewmodel class somehow. When the viewmodel is posted back to the controller on say adding an entry to a list of the viewmodels, it is passed into the parameter of the controller method. I would like to have the date service passed into the viewmodel automatically at that point.
Does anyone know how this can be achieved? I'm using Mvc3 with StructureMap.
I wouldn't do such calculations on the view model. On the view model I would stick with POCO properties. I would perform this calculation at the moment I map my domain model to the view model. This could be done either in the controller action or in the mapping layer where you have access to the service layer.
Instead of writing a method in viewmodel to validate the DOB, you could write a custom DOB validator like:
public static ValidationResult DOBValidator(DateTime DOB)
{
if (DOB!= null && DOB.Date != DateTime.MinValue.Date)
{
int age = DateTime.Now.Year - DOB.Year;
if (age < 18)
{
return new ValidationResult("Sorry, age should be more than 18 years");
}
}
return ValidationResult.Success;
}
}
you can then decorate you DOB property in viewmodel with something like:
[CustomValidation(typeof(ViewModelClassName), "DOBValidator")]
and in you unit test, you could just call the viewmodel method and pass a dummy datetime value:
DateTime testDOB = DateTime.Now.AddYears(-18);
ValidationResult result = ViewModelObject.DOBValidator(testDOB);
Assert.AreEqual(ValidationResult.Success, result, "The ValidationResult was incorrect");
Hope this helps.
精彩评论