如何使用支持ASP.NET Core中的依赖项注入的自定义模型绑定器? [英] How do I use custom model binder that supports dependency injection in ASP.NET Core?

查看:109
本文介绍了如何使用支持ASP.NET Core中的依赖项注入的自定义模型绑定器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MVC中使用自定义模型绑定程序,该绑定程序需要从IoC容器中解析.我遇到的问题是,在添加MVC服务时无法访问我的容器,因为还没有构建我的容器(并且我需要在构建容器之前添加MVC).感觉就像是鸡/蛋问题,我敢肯定我错过了一个简单的解决方案.

I am trying to use a custom model binder in MVC that I want resolved from my IoC container. The issue I am having is that I can't access my container while I am adding the MVC service, because my container isn't built yet (and I need to add MVC before building my container). Feels like a chicken/egg issue, and I am sure I am missing a simple solution.

示例:

services.AddMvc().AddMvcOptions(options =>
{
     options.ModelBinders.Add(serviceProvider.Resolve<CustomModelBinder>());
});

我的自定义模型活页夹看起来像这样:

My custom model binder looks like this:

public class CustomModelBinder : IModelBinder
{
    private IServiceProvider serviceProvider;

    public CustomModelBinder(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {
        var model = serviceProvider.GetService(bindingContext.ModelType);
        bindingContext.Model = model;

        var binder = new GenericModelBinder();
        return binder.BindModelAsync(bindingContext);
    }
}

推荐答案

在此发布文章: https ://github.com/aspnet/Mvc/issues/4167

要直接回答您的问题,请使用:

To answer your question directly, use:

bindingContext.OperationBindingContext.ActionContext.HttpContext.RequestServices

另一方面,您还可以选择使用[FromServices]为您解决该问题.

On a side note, you also have the option of using [FromServices] to resolve it for you.

这篇关于如何使用支持ASP.NET Core中的依赖项注入的自定义模型绑定器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆