inheritancebindingninjectcontextual-binding

Ninject Binding "all inheriting from x"


Pretty usual scenario:

public class A { }
public class B:A {}
public class C:A {}

I really wonder if it is possible to create Ninject Bindings that resolve all inheriting from A like the following:

Bind<A>().ToMethod(ctx => proxyFactory.CreateProxy(ctx.Request.Service) as A);

This of course only works for Requests on type A. Requests for B and C are handled the default way.

Thanks in advance


Solution

  • If it's a possibility to add ninject.extensions.conventions, you can bind them dynamically like this:

    kernel.Bind(x => x
        .FromThisAssembly()
        .SelectAllClasses()
        .InheritedFrom<A>()
        .BindBase()
        .Configure(c => c.InTransientScope()));