【发布时间】:2016-06-22 20:30:43
【问题描述】:
我有一个想要在所有页面上使用的存储库。
默认情况下,所有 MVC 控制器都继承自 Controller 类。我创建了CustomBaseController 类,在其中为Repository 定义了字段,并在CustomBaseController 构造函数中实例化了带有上下文的repo。
但是,当我想创建一个新控制器时,例如继承自 CustomBaseController 的 HomeController,我的存储库字段 (db) 不可见。
这是我的新 CustomBaseController 的示例:
public class CustomBaseController : Controller {
private IRepository db; // <-- defined
public CustomController() {
// here it is initialized
db = new DbRepository(new ApplicationDBContext());
}
}
还有来自我的HomeController:
public class ProgramController : CustomBaseController
{
// GET: Program
public ActionResult Index()
{
// db is not accessible here for some reason,
// like it wasn't inherited from CustomBaseController
var user = db.getUserByID(1);
return List(user);
}
...
【问题讨论】:
-
所以让它受到保护。
标签: c# asp.net-mvc entity-framework inheritance controller