我正在尝试测试一个仅使用列表和创建的非常简单的表单。这是 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
只是我创建的一个模拟存储库,用于测试依赖注入(inject)。每当我尝试创建新条目时,我都会被发送回索引 View ,但新条目不会添加到列表中。使用调试器,它显示每次我单击链接或导航到 Controller 控件内的链接时都会调用构造函数。有没有办法解决这个问题?我有一种我做错了的感觉。我正在尝试做的是使用 Ninject 进行依赖注入(inject),但到目前为止我被困在这个问题上。
最佳答案
为什么这是一个问题 - 这是 ASP.NET 请求的工作方式。每个请求都会运行它自己的 asp.net 页面实例或 MVC Controller ,当请求完成时, Controller 会被丢弃 - 这些东西在请求之间都不会持续存在。
因此,在您的创建方法中,您应该在添加新位置后调用存储库的保存/提交方法。
关于asp.net-mvc - 在每个请求上调用 Controller 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1378019/