首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVC 6自定义模型绑定器的依赖注入

MVC 6自定义模型绑定器的依赖注入
EN

Stack Overflow用户
提问于 2016-02-25 00:34:44
回答 2查看 5.4K关注 0票数 9

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

代码语言:javascript
运行
复制
public class MyViewModel
{
    private readonly IMyService myService;

    public ClaimantSearchViewModel(IMyService myService)
    {
        this.myService = myService;
    }
}

使用此ControllerViewModel如下所示:

代码语言:javascript
运行
复制
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看起来是这样的:

代码语言:javascript
运行
复制
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方法很好(使用

代码语言:javascript
运行
复制
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource(x => x.Name.Contains("ViewModel")));

在我的Startup class中),但是执行POSTIndex(MyViewModel model)的操作会给您一个No parameterless constructor defined for this object异常。我意识到可以使用我的custom model binderDI将是最有可能的解决方案.但我找不到任何关于如何开始这里的帮助。请帮助我,特别是Autofac in MVC 6

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-26 20:17:30

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

答案是使用: FromServices

我的模特最后看起来是这样:

代码语言:javascript
运行
复制
public class MyViewModel
{
    [FromServices]
    public IMyService myService { get; set; }

    public ClaimantSearchViewModel(IMyService myService)
    {
        this.myService = myService;
    }
}

虽然让这个属性成为public是很悲哀的,但它比不得不使用custom model binder要少得多。

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

代码语言:javascript
运行
复制
public class MyController : Controller
{
    ... same as in OP

    [HttpPost]
    public IActionResult Index([FromServices]MyViewModel model)
    {
        return View(model);
    }
}

更新1

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

代码语言:javascript
运行
复制
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方法中注册:

代码语言:javascript
运行
复制
        services.AddMvc().AddMvcOptions(options =>
        {
            options.ModelBinders.Clear();
            options.ModelBinders.Add(new IoCModelBinder());

        });

就是这样。(甚至不确定是否需要options.ModelBinders.Clear();。)

UPDATE 2在经过多次迭代以使其正常工作(使用帮助https://github.com/aspnet/Mvc/issues/4196)之后,最后的结果如下:

代码语言:javascript
运行
复制
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,我们的注册:

代码语言:javascript
运行
复制
        services.AddMvc().AddMvcOptions(options =>
        {
            options.ModelBinders.Insert(0, new IoCModelBinder());
        });

更新3:这是Model Binder及其ProviderASP.NET Core 2.X一起工作的最新迭代。

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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));
票数 8
EN

Stack Overflow用户

发布于 2021-02-05 00:33:04

这个问题被标记为ASP.NET核心,下面是我们针对DOTNetCore3.1的解决方案。

我们的解决方案概要: TheProject需要将ICustomerService提供给在请求管道中自动创建的对象。需要这样做的类被标记为一个接口IUsesCustomerService。然后由Binder在创建对象时检查这个接口,并处理特例。

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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());
        });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35616035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档