具有依赖关系注入的 MVC 6 自定义模型绑定器

本文关键字:自定义 模型 绑定 MVC 依赖 关系 注入 | 更新日期: 2023-09-27 18:36:09

现在我的ViewModel看起来像这样:

public class MyViewModel
{
    private readonly IMyService myService;
    public ClaimantSearchViewModel(IMyService myService)
    {
        this.myService = myService;
    }
}

我消耗此ViewModelController如下所示:

public class MyController : Controller
{
    private readonly IMyService myService;
    public HomeController(IMyService myService)
    {
        this.myService = myService;
    }
    public IActionResult Index()
    {
        var model = new MyViewModel(myService);
        return View(model);
    }
    [HttpPost]
    public async Task<IActionResult> Find()
    {
        var model = new MyViewModel(myService);
        await TryUpdateModelAsync(model);
        return View("Index", model);
    }
}

我需要的是我的Controller看起来像这样:

public class MyController : Controller
{
    private readonly IServiceProvider servicePovider;
    public MyController(IServiceProvider servicePovider)
    {
        this.servicePovider = servicePovider;
    }
    public IActionResult Index()
    {
        var model = servicePovider.GetService(typeof(MyViewModel));
        return View(model);
    }
    [HttpPost]
    public IActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

现在,调用第一个Index方法工作正常(使用

builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource(x => x.Name.Contains("ViewModel")));

在我的Startup class中),但是POST Index(MyViewModel model)会给你一个No parameterless constructor defined for this object例外。我意识到可以使用我的DI custom model binder将是最有可能的解决方案......但我甚至无法找到有关如何从这里开始的任何帮助。请帮助我解决这个问题,特别是对于MVC 6Autofac.

具有依赖关系注入的 MVC 6 自定义模型绑定器

我们在这里得到了答案:https://github.com/aspnet/Mvc/issues/4167

答案是使用:[来自服务]

我的模型最终看起来像这样:

public class MyViewModel
{
    [FromServices]
    public IMyService myService { get; set; }
    public ClaimantSearchViewModel(IMyService myService)
    {
        this.myService = myService;
    }
}

虽然让该属性public很难过,但这比不得不使用custom model binder要难过得多。

此外,据说您应该能够将[FromServices]作为 Action 方法中的参数的一部分传递,它确实解析了类,但这会破坏模型绑定......即我的财产都没有被映射。它看起来像这样:(但同样,这不起作用,所以使用上面的例子)

public class MyController : Controller
{
    ... same as in OP
    [HttpPost]
    public IActionResult Index([FromServices]MyViewModel model)
    {
        return View(model);
    }
}

更新 1

在使用 [FromServices ] 属性后,我们决定在所有ViewModels中注入属性不是我们想要的方式,尤其是在考虑通过测试进行长期维护时。因此,我们决定删除[FromServices]属性,并使我们的自定义模型绑定器正常工作:

public class IoCModelBinder : IModelBinder
{
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {
        var serviceProvider = bindingContext.OperationBindingContext.HttpContext.RequestServices;
        var model = serviceProvider.GetService(bindingContext.ModelType);
        bindingContext.Model = model;
        var binder = new GenericModelBinder();
        return binder.BindModelAsync(bindingContext);
    }
}

它在Startup ConfigureServices方法中注册如下:

        services.AddMvc().AddMvcOptions(options =>
        {
            options.ModelBinders.Clear();
            options.ModelBinders.Add(new IoCModelBinder());
        });

仅此而已。(甚至不确定是否需要options.ModelBinders.Clear();

更新 2在经历了各种迭代使其工作(在 https://github.com/aspnet/Mvc/issues/4196 的帮助下)之后,这是最终结果:

public class IoCModelBinder : IModelBinder
{
    public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {   // For reference: https://github.com/aspnet/Mvc/issues/4196
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));
        if (bindingContext.Model == null && // This binder only constructs viewmodels, avoid infinite recursion.
                (
                    (bindingContext.ModelType.Namespace.StartsWith("OUR.SOLUTION.Web.ViewModels") && bindingContext.ModelType.IsClass)
                        ||
                    (bindingContext.ModelType.IsInterface)
                )
            )
        {
            var serviceProvider = bindingContext.OperationBindingContext.HttpContext.RequestServices;
            var model = serviceProvider.GetRequiredService(bindingContext.ModelType);
            // Call model binding recursively to set properties
            bindingContext.Model = model;
            var result = await bindingContext.OperationBindingContext.ModelBinder.BindModelAsync(bindingContext);
            bindingContext.ValidationState[model] = new ValidationStateEntry() { SuppressValidation = true };
            return result;
        }
        return await ModelBindingResult.NoResultAsync;
    }
}

您显然希望将OUR.SOLUTION...替换为适合您的ViewModels的任何namespace 我们的注册:

        services.AddMvc().AddMvcOptions(options =>
        {
            options.ModelBinders.Insert(0, new IoCModelBinder());
        });

更新 3:这是Model Binder及其Provider的最新版本,适用于ASP.NET Core 2.X

public class IocModelBinder : ComplexTypeModelBinder
{
    public IocModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders, ILoggerFactory loggerFactory) : base(propertyBinders, loggerFactory)
    {
    }
    protected override object CreateModel(ModelBindingContext bindingContext)
    {
        object model = bindingContext.HttpContext.RequestServices.GetService(bindingContext.ModelType) ?? base.CreateModel(bindingContext);
        if (bindingContext.HttpContext.Request.Method == "GET")
            bindingContext.ValidationState[model] = new ValidationStateEntry { SuppressValidation = true };
        return model;
    }
}
public class IocModelBinderProvider : IModelBinderProvider
{
    private readonly ILoggerFactory loggerFactory;
    public IocModelBinderProvider(ILoggerFactory loggerFactory)
    {
        this.loggerFactory = loggerFactory;
    }
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        if (!context.Metadata.IsComplexType || context.Metadata.IsCollectionType) return null;
        var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
        foreach (ModelMetadata property in context.Metadata.Properties)
        {
            propertyBinders.Add(property, context.CreateBinder(property));
        }
        return new IocModelBinder(propertyBinders, loggerFactory);
    }
}

然后在Startup

services.AddMvc(options =>
{
    // add IoC model binder.
    IModelBinderProvider complexBinder = options.ModelBinderProviders.FirstOrDefault(x => x.GetType() == typeof(ComplexTypeModelBinderProvider));
    int complexBinderIndex = options.ModelBinderProviders.IndexOf(complexBinder);
    options.ModelBinderProviders.RemoveAt(complexBinderIndex);
    options.ModelBinderProviders.Insert(complexBinderIndex, new IocModelBinderProvider(loggerFactory));

这个问题被标记为 ASP.NET Core,所以这是我们针对 dotnet core 3.1 的解决方案。

我们的解决方案概述:TheProject 需要使ICustomerService可用于在请求管道中自动创建的对象。需要此功能的类使用接口 IUsesCustomerService 标记。然后,Binder 在创建对象时检查此接口,并处理特殊情况。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
namespace TheProject.Infrastructure.DependencyInjection
{
    /// <summary>
    /// This is a simple pass through class to the binder class.
    /// It gathers some information from the context and passes it along.
    /// </summary>
    public class TheProjectModelBinderProvider : IModelBinderProvider
    {
        public TheProjectModelBinderProvider()
        {
        }
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            ILoggerFactory ilogger;
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            // The Binder that gets returned is a <ComplexTypeModelBinder>, but I'm
            // not sure what side effects returning early here might cause.
            if (!context.Metadata.IsComplexType || context.Metadata.IsCollectionType)
            {
                return null;
            }
            var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
            foreach (ModelMetadata property in context.Metadata.Properties)
            {
                propertyBinders.Add(property, context.CreateBinder(property));
            }
            ilogger = (ILoggerFactory)context.Services.GetService(typeof(ILoggerFactory));
            return new TheProjectModelBinder(propertyBinders, ilogger);
        }
    }
    
    /// <summary>
    /// Custom model binder.
    /// Allows interception of endpoint method to adjust object construction
    /// (allows automatically setting properties on an object that ASP.NET creates for the endpoint).
    /// Here this is used to make sure the <see cref="ICustomerService"/> is set correctly.
    /// </summary>
    public class TheProjectModelBinder : ComplexTypeModelBinder
    {
        public TheProjectModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders, ILoggerFactory loggerFactory)
            : base(propertyBinders, loggerFactory)
        {
        }
        /// <summary>
        /// Method to construct an object. This normally calls the default constructor.
        /// This method does not set property values, setting those are handled elsewhere in the pipeline,
        /// with the exception of any special properties handled here.
        /// </summary>
        /// <param name="bindingContext">Context.</param>
        /// <returns>Newly created object.</returns>
        protected override object CreateModel(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
                throw new ArgumentNullException(nameof(bindingContext));
            var customerService = (ICustomerService)bindingContext.HttpContext.RequestServices.GetService(typeof(ICustomerService));
            bool setcustomerService = false;
            object model;
            if (typeof(IUsesCustomerService).IsAssignableFrom(bindingContext.ModelType))
            {
                setcustomerService = true;
            }
            
            // I think you can also just call Activator.CreateInstance here.
            // The end result is an object that's constructed, but no properties are set yet.
            model = base.CreateModel(bindingContext);
            if (setcustomerService)
            {
                ((IUsesCustomerService)model).SetcustomerService(customerService);
            }
            return model;
        }
    }
}

然后在启动代码中,确保设置AddMvcOptions

public void ConfigureServices(IServiceCollection services)
{
    // ...
    
    // asp.net core 3.1 MVC setup 
    services.AddControllersWithViews()
        .AddApplicationPart(assembly)
        .AddRazorRuntimeCompilation()
        .AddMvcOptions(options =>
        {
            IModelBinderProvider complexBinder = options.ModelBinderProviders.FirstOrDefault(x => x.GetType() == typeof(ComplexTypeModelBinderProvider));
            int complexBinderIndex = options.ModelBinderProviders.IndexOf(complexBinder);
            options.ModelBinderProviders.RemoveAt(complexBinderIndex);
            options.ModelBinderProviders.Insert(complexBinderIndex, new Infrastructure.DependencyInjection.TheProjectModelBinderProvider());
        });
}