2016-06-22 4 views
-1

すべてのページで使用したいリポジトリがあります。C#MVC 5継承するカスタムコントローラクラス

デフォルトでは、すべてのMVCコントローラはControllerクラスを継承します。私はRepositoryのフィールドを定義したCustomBaseControllerクラスを作成し、CustomBaseControllerコンストラクタのコンテキストでインスタンス化しました。

これまで、新しいコントローラを作成したいときなど。 HomeControllerCustomBaseControllerから継承されていますが、私のリポジトリフィールド(db)は表示されません。ここで

は私の新しいCustomBaseControllerからの例です:私のHomeControllerからも

public class CustomBaseController : Controller { 
    private IRepository db; // <-- defined 
    public CustomController() { 
     // here it is initialized 
     db = new DbRepository(new ApplicationDBContext()); 
    } 
} 

そして:

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); 
    } 
... 
+2

それで保護してください。 –

答えて

0

protected代わりprivateのごIRepositoryフィールドを作成し、それが子クラスに表示されます。

+0

はい、ちょうどそれが気づいた - .-、これは私の端から脳のおならのケースでした – Reygoch

0

いいえ、問題が見つかりました。私は偶然に自分のレポ変数をプライベートにしました