Search code examples
c#-4.0ninjectninject-2

How to provide injection for method which is called in NinjectModule


I have the following NinjectModule derived class:

class MainModule : NinjectModule 
{
    public override void Load()
    {
        Bind<IMyClass>().To<MyClass>();

        Bind<IMainClass>().To<MainClass>().OnActivation((context,myClass) => 
        { myClass.Add("Something", context.Kernel.Get<IMyClass>());  });
    }
}

My problem is that IKernel does not exposed the .Get<T> extension method.

Is there a pattern for doing this?

Caveats: I don't want to have to decorate my classes with Ninject attributes, as the Add is specific to how MainClass works I wanted all the code to do with its creation to be held in this module.

TIA


Solution

  • Hmmm, silly oversight in the end it seems. The extension methods reside in the Ninject namespace, using a module only requires that you are using Ninject.Modules;

    Adding using Ninject; meant that the following was possible:

    Bind<IMainClass>().To<MainClass>()
    .OnActivation((context,myClass) => 
    { 
        foreach(var n in context.Kernel.GetAll<IMyClass>())
        {
            myClass.Add("Something", n);  
        }
    });
    

    I'll leave this open for a bit to see if anyone has a better way of doing this.