Service being null in controller

Asked

Viewed 73 times

0

When performing a post for my controller, when debugging, I saw that the service I load in my constructor, is coming type null.

Controller:

public class UserController : ApiController
{
    private static IUserService _userService;

    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    [System.Web.Http.HttpGet]
    public IHttpActionResult GetUserById(long id)
    {
        var user = _userService.GetById(id);
        return Ok(user);
    }

    [HttpPost]
    [Route("api/User/Insert")]
    public IHttpActionResult Insert(User user)
    {
        user.StartDate = DateTime.Now;
        _userService.Register(user);

        return Ok();
    }
}

Return of debbug error:

Controller' does not have a default constructor","Exception Type":"System.Argumentexception","Stacktrace"

  • You initialize the UserController at some point?

  • 1

    What dependency injection strategy do you use?

  • @Diegorafaelsouza was trying to inject into Webapiconfig.Cs, but it was unsuccessful. So, it’s none.

  • So there’s no way it’s gonna work unless you declare such a default constructor, like,: public UserController() : this(new UserServiceImplementation()) { }

  • That way it doesn’t work.

1 answer

1

You can initialize your service in the constructor default of your Controller:

public class UserController : ApiController
{
    private IUserService _userService;

    public UserController()
    {
        _userService =  new UserService();
    }

    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    [System.Web.Http.HttpGet]
    public IHttpActionResult GetUserById(long id)
    {
        var user = _userService.GetById(id);
        return Ok(user);
    }

    [HttpPost]
    [Route("api/User/Insert")]
    public IHttpActionResult Insert(User user)
    {
        user.StartDate = DateTime.Now;
        _userService.Register(user);

        return Ok();
    }
}

If you are interested in using some dependency injection strategy, there are some container’s very useful today. Among them are Unity and Ninject. Below an example of someone who had the same problem as you and his case is dealt with Ninject. Follow link: Ninject for Dependency Injection

Browser other questions tagged

You are not signed in. Login or sign up in order to post.