MR.ABC
MR.ABC

Reputation: 4862

Ninject Singleton Factory

I have a interface that is binded to a class. Everything work like excepted. I want to create the class with a constructor injection without passing my kernel everywhere. I want to have a singleton factory for these propose. How can i create one without using the ninject.extensions.factory library.

Upvotes: 0

Views: 798

Answers (2)

Adam Rodger
Adam Rodger

Reputation: 3562

If you want to create a factory but without using the Factory Extension (not sure why, it's exactly what you need here I think) you can do something like the following:

public class FooFactory : IFooFactory
{
    // allows us to Get things from the kernel, but not add new bindings etc.
    private readonly IResolutionRoot resolutionRoot;

    public FooFactory(IResolutionRoot resolutionRoot)
    {
        this.resolutionRoot = resolutionRoot;
    }

    public IFoo CreateFoo()
    {
        return this.resolutionRoot.Get<IFoo>();
    }

    // or if you want to specify a value at runtime...

    public IFoo CreateFoo(string myArg)
    {
        return this.resolutionRoot.Get<IFoo>(new ConstructorArgument("myArg", myArg));
    }
}

public class Foo : IFoo { ... }

public class NeedsFooAtRuntime
{
    public NeedsFooAtRuntime(IFooFactory factory)
    {
        this.foo = factory.CreateFoo("test");
    }
}

Bind<IFooFactory>().To<FooFactory>();
Bind<IFoo>().To<Foo>();

The Factory Extension just does all of that work for you at runtime though. You only need to define the factory interface and the extension creates the implementation dynamically.

Upvotes: 2

Roi Shabtai
Roi Shabtai

Reputation: 3075

Try this code:

class NinjectKernelSingleton
{
    private static YourKernel _kernel;

    public static YourKernel Kernel
    {
        get { return _kernel ?? (_kernel = new YourKernel()); }
    }

}

public class YourKernel
{
    private IKernel _kernel;
    public YourKernel()
    {
        _kernel = InitKernel();
    }

    private IKernel InitKernel()
    {
        //Ninject init logic goes here
    }

    public T Resolve<T>() 
    {
        return _kernel.Get<T>();
    }
}

Upvotes: 0

Related Questions