Inheriting a base controller with constructor

一曲冷凌霜 提交于 2019-12-06 15:50:47

C# requires that if your base class hasn't a default constructor than you have to add a constructor to your derived class. E.g.

public class HomeController : BaseController
{
    public HomeController(IRepository<string> db) : base(db) { }

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

The dependency is then provided by Ninject if you have the required binding:

Bind<IRepository<string>>().To<Repository<string>();

Your BaseController should not take a concrete Repository but the interface.

public class BaseController : Controller
{
    public IRepository<string> db;

    public BaseController(IRepository<string> db){
        this.db = db;
        Debug.WriteLine("Repository True");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!