哪里是声明控制器中使用的实体和服务的最佳位置?在构造函数或操作中?
public class CourseController : Controller
{
MyEntities entities; //DECLARE THIS HERE?
private readonly IMyService _service; //DECLARE THIS HERE?
public MyController()
{
entities = new MyEntities(); //INITIALIZE HERE?
_service = new MyService(_entities); //INITIALIZE HERE?
}
public ActionResult Detail(int ID)
{
using (MyEntities _entities = new MyEntities ()) //OR DECLARE AND INITILIZE HERE?
{
IMyService _service = new MyService(_entities); //OR DECLARE AND INITILIZE HERE?
var myCourse = _service.GetCourseById(ID);
return View(myCourse);
}
}
}
答案 0 :(得分:0)
我会在构造函数中声明它们并提供重载,以便我可以为单元测试目的注入假货。
private readonly MyEntities entities;
private readonly IMyService _service;
public MyController()
{
_entities = new MyEntities();
_service = new MyService(_entities);
}
public MyController(MyEntities myEntities, IMyService myService)
{
entities = myEntities;
_service = myService;
}