Service being loaded null in the controller

0

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

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

Debug error return:

  

Controller 'does not have a default constructor', 'Exception Type': "System.ArgumentException", "StackTrace"

    
asked by anonymous 20.02.2018 / 20:01

1 answer

1

You can initialize your service in the default constructor 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 very useful containers today. Among them are the Unity and Ninject. Below is an example of someone who has had the same problem as you and his case is treated with Ninject. Here's the link: Ninject for Dependency Injection

    
20.02.2018 / 21:41