【问题标题】:C# MVC 5 Custom controller class to inherit fromC# MVC 5 要继承的自定义控制器类
【发布时间】: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


【解决方案1】:

将IRepository 字段设为protected 而不是private,它将在子类中可见。

【讨论】:

  • 是的,刚刚注意到-.-,这是我脑中放屁的案例
【解决方案2】:

好的,找到问题了。我无意中将我的 repo 变量设为私有

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    相关资源
    最近更新 更多