Multiple Ninject Modules giving odd behaviour

120 Views Asked by At

This one is a little complex but reproducible in my environment. Architecture as follows;

BindingsLayer
    +-NinjectBindingsModule
    +-NinjectWebBindingsModule

ContractsLayer
    +- ISomeService
    +- IAnotherService

DomainLayer
    +- SomeService : ISomeService
    +- AnotherService : IAnotherService
       {
           public AnotherService(ISomeService) {}
       }

PersistenceLayer
    +- PBADBEntities (Entity framework context)

WebProjectA
    +- Uses bindings in NinjectWebBindingsModule

ConsoleProjectB
    +- Uses bindings in NinjectBindingsModule

Ninject module implementation

class NinjectBindingsModule : NinjectModule
{
    public override void Load()
    {
            Bind<PBADBEntities>().ToSelf();
            Kernel.Bind(s => s.FromAssembliesMatching("MySolution.*.dll")
                              .SelectAllClasses()
                              .BindDefaultInterfaces()
                       );
    }
}

class NinjectWebBindingsModule : NinjectModule
{
    public override void Load()
    {
            Bind<PBADBEntities>().ToSelf();
            Kernel.Bind(s => s.FromAssembliesMatching("MySolution.*.dll")
                              .SelectAllClasses()
                              .BindDefaultInterfaces()
                              .InRequestScope()
                       );
    }
}

Now, the above breaks for me if I run the web project with the following error;

Error activating ISomeService. No matching bindings are available, and the type is not self-bindable.

However, if I change the bindings in NinjectBindingsModule (for the console application, not the web project which is being run), to the following;

class NinjectBindingsModule : NinjectModule
{
    public override void Load()
    {
            Bind<PBADBEntities>().ToSelf();
            Bind<ISomeService>().To<SomeService>();
            Bind<IAnotherService>().To<AnotherService>();
    }
}

Then the web project works correctly. There is no explicit reference to the NinjectBindingsModule class from the web project and neither does any breakpoint get hit if I put one in there. A breakpoint will get hit if I put it in NinjectWebBindings and continue on normally.

This would imply that Ninject is loading up or otherwise scanning all modules in referenced assemblies and doing something with them in regard to binding. Any ideas on how to resolve this without having a separate project per module?

1

There are 1 best solutions below

0
On BEST ANSWER

This post is an old one but I thought I'd post the answer here. The issue turned out to be a bug in Ninject that was later fixed as of version 3.2.1. Using the architecture above for other solutions with later versions worked just fine and issue disappeared. In a nutshell, upgrade Ninject if you can.