Search code examples
c#wpfdependency-injectionninjectninject-extensions

Injecting concrete instance into Ninject resolver


Its easy enough using NInject to establish dependency injection using interfaces.

So for example say I have a class like

public class WindowManagerService : IWindowManager 
{
    public WindowManagerService(ILogger logger) { }
}

It's easy to do something like this:

public class NinjectModuleLoader : NinjectModule
{
    public override void Load()
    {
        this.Bind<IWindowManager>().To<WindowManagerService>().InSingletonScope();
    }
}

and successfully configure the dependency injection.

However the problem I run into is when I need to provide a concrete instance of a class into the constructor such as the following example:

public class ObservableLogger : ILogger
{
    public ObservableLogger(Dispatcher dispatcher) { }
}

In the above example I require the ability to pass in a concrete implementation of the dispatcher as I cannot use DI to establish this link and must reference the application wide Dispatcher instance.

Essentially what I wish to be able to do is something like this:

this.Bind<ILogger>().To(new ObservableLogger(Dispatcher)).InSingletonScope();

So how does one provide concrete implementations of dependencies to the NInject dependency manager?


Solution

  • You could use a factory method:

    this.Bind<ILogger>().ToMethod(context => new ObservableLogger(Dispatcher));
    

    ...or create your own custom provider as explained in the docs: https://github.com/ninject/Ninject/wiki/Providers,-Factory-Methods-and-the-Activation-Context

    There is also the ToConstant and ToConstructor methods:

    this.Bind<ILogger>().ToConstant(new ObservableLogger(Dispatcher));
    

    Please refer to this blog post for more information.