JMarsch
JMarsch

Reputation: 21753

Ninject: Inject all subclasses

Ok, so I've seen how I can use kernel.GetAll to get back instances of every class that implements an interface. (well documented under multi-injection here: https://github.com/ninject/Ninject/wiki/Multi-injection)

What if I want to do almost the same thing, but I want for it to inject all inheritors of a subclass?

var instances = kernel.GetAll<ParentClass>(); // or something equivalent?

I've tried the code above. It doesn't throw, but it doesn't return any instances either.

Upvotes: 1

Views: 200

Answers (1)

Owen Pauling
Owen Pauling

Reputation: 11841

You need to bind the base class to each of the derived classes like so:

kernel.Bind<ParentClass>().To<ClassA>();
kernel.Bind<ParentClass>().To<ClassB>();
var instances = kernel.GetAll<ParentClass>();

Upvotes: 1

Related Questions