Grizzly
Grizzly

Reputation: 5943

Runtime Null Reference Exception Using SimpleInjector in WebApi Controller

In my MVC project, I have an API controller that I want to use dependency injection for. I am using Simple Injector for dependency injection.

Here is my api controller:

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();
        }

When debugging, the runtime error is occurring on the else if statement stating:

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

and

_dbContext=null

Can dependency injection be used with api controllers? I assumed they could?

Any explanation or help as to why this is happening is greatly appreciated.

Upvotes: 1

Views: 387

Answers (1)

Nkosi
Nkosi

Reputation: 247098

The default constructor is being called, so the context is not being injected. Hence the null

Remove the default constructor from the ApiController and keep the follow

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

also ensure that the IDiContext is properly registered with the DI container

Reference ASP.NET Web API Integration Guide for Simple Injector

Upvotes: 3

Related Questions