Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection (DI) in ASP.NET Core/MVC 6 ViewModel

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.

like image 666
Dave Avatar asked Feb 20 '16 02:02

Dave


1 Answers

Thank you to @odeToCode for the answer. For the sake of completeness I re-post his comment as the answer with my (working) example. The magic is the [FromServices] attribute.

public class CreateDynamicMappingProfileViewModel : IValidatableObject
{

    [Display(Name = "Name", Order = 1), Required, MaxLength(50, ErrorMessage = "The name field allows a maximum of 50 characters")]
    public string Name { get; set; }

    [Display(Name = "Data Format", Order = 2), Required]
    public DataFormat DataFormat { get; set; }

    [Display(Name = "Data Context", Order = 3), Required]
    public DataContextType DataContextType { get; set; }

    [FromServices]
    public IMappingProfileServices MappingProfileServices { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        IMappingProfile mappingProfile = new DynamicMappingProfile(Name, DataFormat, DataContextType);
        return MappingProfileServices.ValidateCanSave(mappingProfile);
    }
}
like image 137
Dave Avatar answered Nov 13 '22 18:11

Dave