WebApi 控制器中使用 SimpleInjector 的运行时空引用异常

Runtime Null Reference Exception Using SimpleInjector in WebApi Controller

在我的 MVC 项目中,我有一个 API 控制器,我想对其使用依赖注入。我正在使用 Simple Injector 进行依赖注入。

这是我的 api 控制器:

public class MedicInfoesApiController : ApiController
{
    private readonly IDiContext _dbContext;

    public MedicInfoesApiController() { }

    public MedicInfoesApiController(IDiContext diContext)
    {
        _dbContext = diContext;
    }

    // POST: api/MedicInfoesApi
    [ResponseType(typeof(MedicInfo))]
    public IHttpActionResult PostMedicInfo(MedicInfo medicInfo)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // Create empty Employee Object to get info of person being submitted via IBM
        Employee emp = new Employee();

        //check if IBM that user is submitting exists
        if (!EmployeeData.IsValidIBM(medicInfo.MedicIbm))
        {
            ModelState.AddModelError("", "This IBM does not exist!");
        }
        // Check if any existing IBM's match what the user is trying to submit... if none then save to database
        else if (_dbContext.GainAccess().MedicInfoes.Any(x => x.MedicIbm.Equals(medicInfo.MedicIbm, StringComparison.CurrentCultureIgnoreCase)))
        {
            ModelState.AddModelError("", "This person already exists!");
        }

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        else
        {
            // Set empty Employee object with Data of person
            emp = EmployeeData.GetEmployee(medicInfo.MedicIbm);
            medicInfo.Active = true;
            _dbContext.GainAccess().MedicInfoes.Add(medicInfo);

            _dbContext.GainAccess().SaveChanges();
        }

调试时,运行时错误发生在 else if 语句上,指出:

x.MedicIbm=error CS0103: The name 'x' does not exist in the current context

_dbContext=null

依赖注入可以与 api 控制器一起使用吗?我以为他们可以?

非常感谢任何关于为什么会发生这种情况的解释或帮助。

正在调用默认构造函数,因此未注入上下文。因此 null

ApiController 中删除默认构造函数并保留以下

public MedicInfoesApiController(IDiContext diContext) {
    _dbContext = diContext;
}

还要确保 IDiContext 已正确注册到 DI 容器

引用ASP.NET Web API Integration Guide for Simple Injector