注入 IEnumerable<IInputFormatters>

Inject IEnumerable<IInputFormatters>

我很难尝试将 IEnumerable<IInputFormatters> 注入其他服务。 我已经注册了自己的 InputFromatter 并且还添加了 JsonFormatters。所以,至少应该有 3 个输入格式化程序,但是当我尝试注入 IEnumerable<IInputFormatters> 时,我不断得到 null(就像根本没有格式化程序一样)。 我的注册看起来像:

services.AddMvcCore(config =>
            {
                config.InputFormatters.Insert(0, new UserContextFormatter());
                config.ModelBinderProviders.Insert(0, new ModelBinderProvider());
            })
                .AddAuthorization()
                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>())
                .AddJsonOptions(opt =>
                {
                    opt.SerializerSettings.Formatting = Formatting.Indented;
                    opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    opt.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                    opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                })
                .AddJsonFormatters()
                .AddApiExplorer();

看似简单又愚蠢的事情,但我还不够好。有任何想法吗? 谢谢!

对于 IEnumerable<IInputFormatters>,它未注册为服务,因此您无法解析它或从依赖注入访问它。

对于 InputFormattersModelBinderProviders,它们附加到 Action<MvcOptions> setupAction,因此您可以从 IOptions<MvcOptions> 访问它们。

试试下面的代码:

    public class HomeController : ControllerBase
{
    private readonly MvcOptions _options;
    public HomeController(IOptions<MvcOptions> options)
    {
        _options = options.Value;
        var inputFormatters = _options.InputFormatters;
        var outputFormatters = _options.OutputFormatters;
        var modelBinderProviders = _options.ModelBinderProviders;
    }