views:

147

answers:

2

Hey everyone,

I'm on a roll today with questions.

I'm starting out with Dependency Injection and am having some trouble injecting a dependency into a base class.

I have a BaseController controller which my other controllers inherit from. Inside of this base controller I do a number of checks such as determining if the user has the right privileges to view the current page, checking for the existence of some session variables etc.

I have a dependency inside of this base controller that I'd like to inject using Ninject however when I set this up as I would for my other dependencies I'm told by the compiler that:

Error 1 'MyProject.Controllers.BaseController' does not contain a constructor that takes 0 argument

This makes sense but I'm just not sure how to inject this dependency. Should I be using this pattern of using a base controller at all or should I be doing this in a more efficient/correct way?

+3  A: 

your BaseController constructor should be like this

BacseConctoller(Info info)
{
    this.info = info
}

then for all inheritence class their constructor

ChildController(Info info):base(info)
{
}

in this case you can inject Info object to the base controller class

Arseny
A: 

Mark is right on the money,

BaseClass(dependantObject object)
{
 Object = object;
}

so to fulfill the dependantObject so all the subclasses can get access to the base behavior, we can use the injection on the subclass and simply chain the base constructor, passing in our 'Ninjected' object.

 SubClass() : this(null) {}

 SubClass(dependantObject object) : base(object)
  {

  }

happy coding!

Gnostus