Ninject injection not working on subclasses

629 Views Asked by At

I'm trying to add a binding on third level sub-class but I can't find a proper way to do it. I'm using the Ninject 3.0 and I have following scenario:

public class ClassBase 
{
  [Inject]
  public IRepository RepositoryInstance { get; set; }
}

public class ClassA : ClassBase {} 
public class ClassB : ClassA {}

public class RepA : IRepository {}
public class RepB : IRepository {}

How do I bind the RepA to ClassBase so ClassA can have that repository, while ClassB should be bound to RepB ?

Thanks

2

There are 2 best solutions below

2
On

As far a I remember, the Inject attribute is deprecated and should not be used. I would use a constructor to inject it or in specific class I wolud use this kind of method IKernel kernel = new StandardKernel(); var samurai = kernel.Get();

as showed here: https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject

1
On

You might use WhenInjectedInto() ninject IBindingWhenSyntax<T> interface.

So, the binding code will look something like

kernel.Bind<IRepository>().To<RepA>().WhenInjectedInto<ClassA>();
kernel.Bind<IRepository>().To<RepB>().WhenInjectedInto<ClassB>();