Jamie Dixon
Jamie Dixon

Reputation: 54021

Injecting a dependency into a base class

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?

Upvotes: 2

Views: 1901

Answers (2)

Jake Kalstad
Jake Kalstad

Reputation: 2065

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!

Upvotes: 1

Arseny
Arseny

Reputation: 7361

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

Upvotes: 11

Related Questions