I'm trying to test a very simple form that uses only a list and a create. This is the controller:
public class PositionsController : Controller
{
private readonly IPositionRepository _positions;
// default constructor
public PositionsController()
{
_positions = new TestPositionRepository();
}
// DI constructor
public PositionsController(IPositionRepository positions)
{
_positions = positions;
}
// get a list of all positions
public ActionResult Index()
{
return View(_positions.GetAllPositions());
}
// get initial create view
public ActionResult Create()
{
return View();
}
// add the new Position to the list
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Position positionToAdd)
{
try
{
_positions.AddPosition(positionToAdd);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
TestPositionRepository is simply a mock repository I've created in order to test out dependency injection. Whenever I try to create a new entry, I get sent back to the index view, but the new entry is not added to the list. Using the debugger, it's showing that the constructor is called every time I click on a link or navigate to a link within the controller's control. Is there a way to fix this problem? I have the feeling that I'm doing it wrong. What I'm trying to do is dependency injection using Ninject but I'm stuck on this problem so far.
Why is this a problem - it's the way ASP.NET requests work. Each request runs up it's own instance of the asp.net page, or the MVC controller, and when the request is done, the controller is discarded - neither of these things persist between requests.
Thus in your create method you should be calling the repository's save/commit method after adding your new position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With