1

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.

1
  • 1
    Could you please provide your DI Registration where you add this dependency. Commented Nov 19, 2018 at 13:38

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

7 Comments

Okay, that was my initial thought. I understand the Null Reference Exception, but if I comment that out, then I receive runtime console errors: "An error occurred when trying to create a controller of type 'MedicInfoesApiController'. Make sure that the controller has a parameterless public constructor."... "Type 'AviationMedicTraining.Controllers.ApiControllers.MedicInfoesApiController' does not have a default constructor"
That is a default error message and does not mean what you think it does. That message is when the framework is unable to create the controller while resolving its dependencies. Did you review the second part of the answer.
Hi @M12Bennett, please follow the ASP.NET Web API integration Guide for Simple Injector, as Nkosi referred to. Without replacing the default DependencyResolver with Simple Injector's SimpleInjectorWebApiDependencyResolver, Simple Injector will not be invoked by Web API.
Perfect. I apologize, I didn't use the bottom of your answer. Thank you!
Sorry, just had something happen again.. so now my api controller method is being hit as expected, but now the record is not being added/saved to the database. I've edited my code to show
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.