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

自作多情 提交于 2019-12-18 03:48:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!