问题
I'm successfully using ASP.NET 5/MVC 6 DI in my controllers using Constructor Injection.
I now have a scenario where I want my View Models to utalise a service in the Validate method when implementing the IValidatableObject.
Constructor injection in the ViewModel does not work because they need a default parameterless constructor. Validation Context.GetService does not work either.
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
MyService myService = (MyService)validationContext.GetService(typeof(MyService));
always results in MyService being null.
ASP.NET 4, I would create ValidatableObjectAdapter, register it via DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapterFactory & then I could use the validationContext to object references to services.
I'm currently using the build in DI container for ASP.NET 5, will move to structuremap at some stage) not that this should matter.
My specific validation is that an object's property (eg, user name) is unique. I want to delegate this test to the service layer.
来源:https://stackoverflow.com/questions/35518476/dependency-injection-di-in-asp-net-core-mvc-6-viewmodel