【发布时间】:2020-07-08 11:18:00
【问题描述】:
我已经实现了一个自定义 InputFormatter (MyInputFormatter):
public class MyInputFormatter : SystemTextJsonInputFormatter
{
private readonly IMyDepenency _mydependency;
public CustomInputFormatter(
JsonOptions options,
ILogger<SystemTextJsonInputFormatter> logger,
IMyDependency myDependency
) : base(options, logger)
{
_mydependency = myDependency ?? throw new ArgumentNullException(nameof(myDependency));
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
//...
}
}
现在,根据the documentation我需要使用如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new MyInputFormatter(...));
});
}
但是,您可以看到我的CustomInputFormatter 需要一些构造函数参数并且需要一些服务,我不清楚如何使用 DI 来解决这些服务。我已经阅读了很多答案/博客/页面,例如this one,但是 inputformatter 没有任何构造函数参数(因此不需要 DI,只需新建一个内联的新实例)或建议以下内容:
public void ConfigureServices(IServiceCollection services)
{
var sp = services.BuildServiceProvider();
services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new MyInputFormatter(
sp.GetService<...>(),
sp.GetService<...>(),
sp.GetService<IMyDependency>(),
));
});
}
但我们不应该从ConfigureServices 调用BuildServiceProvider。
我该怎么做?
【问题讨论】:
-
这能回答你的问题吗? Resolving instances with ASP.NET Core DI
-
Ian Kemp 在您的链接中的回答怎么样?这是完全相同的问题(唯一的区别是他使用的是
ModelValidatorProviders.Add而不是InputFormatters.Insert)
标签: c# .net-core dependency-injection asp.net-core-webapi