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

时间:2018-11-19 13:30:59

标签: c# asp.net-mvc asp.net-web-api dependency-injection simple-injector

在我的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 =错误CS0103:名称“ x”在当前上下文中不存在

  

_dbContext =空

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

对于为什么发生这种情况的任何解释或帮助,我们深表感谢。

1 个答案:

答案 0 :(得分:3)

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

ApiController中删除默认构造函数,并保持关注

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

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

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