为什么在使用 DI 时在我的新 .NET Core 2.0 WebApi 端点获得 500?

Why getting a 500 at my new .NET Core 2.0 WebApi endpoint when using DI?

我设置了一个新控制器,当我调用端点(大摇大摆)时,我总是得到一个500return编辑。为了检查这不是关于不正确的代码,我只设置了行 return Ok("received"); 当我从控制器构造函数中取出 dependency injection (DI) 时,我得到了 200。 可能有人知道什么可能导致问题以及什么可能是解决方案?

    [Produces("application/json")]
[Route("api/v1/dataPicker/startProcess")]
public class StartProcessController : Controller
{
    private IStartProcessBusinessComponent BusinessComponent { get; }

    public StartProcessController(IStartProcessBusinessComponent startProcessBusinessComponent)
    {
        BusinessComponent = startProcessBusinessComponent;
    }

    [HttpPost()]
    public async Task<IActionResult> SetProcessStart([FromBody]StartProcessWrapper startProcessWrapper)
    {
        return Ok("received");
    }
}



public interface IStartProcessBusinessComponent
{
    Task SetProcessStartAsync(StartProcessWrapper startProcessWrapper);
}


class StartProcessBusinessComponent : IStartProcessBusinessComponent
{
    public StartProcessBusinessComponent( ) {}

    public async Task SetProcessStartAsync(StartProcessWrapper startProcessWrapper) { }
}

当我关闭 DI 时,我得到了 200 returned。 但是我需要DI。

    [Produces("application/json")]
[Route("api/v1/dataPicker/startProcess")]
public class StartProcessController : Controller
{
    private IStartProcessBusinessComponent BusinessComponent { get; }

    public StartProcessController( ) { }

    [HttpPost()]
    public async Task<IActionResult> SetProcessStart([FromBody]StartProcessWrapper startProcessWrapper)
    {
        return Ok("received");
    }
}

需要解决的问题很少

  1. 而是 [FromBody] 使用 [FromServices] 从 DI
  2. 获取组件
  3. 在 DI StartProcessBusinessComponent 中声明为 IStartProcessBusinessComponent 使用例如 services.AddTransient<IStartProcessBusinessComponent, StartProcessBusinessComponent>();

这应该有效