Search code examples
c#.netdependency-injectionninject

Ninject: call a method with each Get call


I have a Singleton Binding on Ninject and I would like to call a method whenever DI resolves it (i.e. with each Get call). Ninject has OnActivation method that is called when the object is resolved only.

I am aware that using Transient scope will be the intuitive solution but due to out-of-control reason. The object must be singleton.


Solution

  • You can achieve this with some trickery. Let me give you an example:

    const string Name = "Foo";
    
    // Singleton Binding. Will only be used when the context uses the {Name}
    Bind<Foo>().To<Foo>()
        .Named(Name)
        .InSingletonScope();
    
    // Unnamed binding with method call on each resolution
    Bind<Foo>().ToMethod(ctx => 
        {
            // Do anything arbitrary here. like calling a method...
            return ctx.Kernel.Get<Foo>(Name));
        });
    

    When Foo (unnamed) is requested from the kernel it will resolve to the ToMethod binding - where you can insert any arbitrary code you like. In the end, the method must use the kernel to request Foo, but this time with a name-condition. This will resolve to the named singleton binding.