Inheriting a base controller with constructor
Asked Answered
V

1

1

I am using ninject to inject my repositories. I would like to have a my base class to be inherited but I cant because it has a constructor.

Base Controller:

namespace Orcha.Web.Controllers
{
    public class BaseController : Controller
    {
        public IRepository<string> db;

        public BaseController(Repository<string> db){
            this.db = db;
            Debug.WriteLine("Repository True");
        }
    }
}

Controller with inherit: Error 'BaseController' does not contain a constructor that takes 0 arguments HomeController.cs

public class HomeController : BaseController
{

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

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}
Vandiver answered 9/8, 2012 at 21:35 Comment(0)
A
6

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");
    }
}
Ashraf answered 10/8, 2012 at 11:11 Comment(1)
that kind of seems redundant. The point of the repository is to not have to put the IRepository on every controller, that it would just inherit it.Vandiver

© 2022 - 2024 — McMap. All rights reserved.