2
votes

I am testing Ninject and trying to understand how to inject repository to singleton class. Below is working repository and singleton class example...

public interface ITestRepository
{
   void TestRepositoryMethod();
}

public class TestRepository:ITestRepository
{
    public void TestRepositoryMethod()
    {

    }
}

public class TestSingletonInjectionClass
{
    private readonly ITestRepository _repository;

    public TestSingletonInjectionClass(
        ITestRepository repository)
    {
        _repository = repository;
    }

    public void TestMethod()
    {

    }
}

The test method which pass sucesfully

[TestMethod]
public void SimpleTestSingleton()
{
    using (IKernel kernel = new StandardKernel())
    {
        kernel.Bind<ITestRepository>().To<TestRepository>();
        var testSingletonInjectionClass = 
            kernel.Get<TestSingletonInjectionClass>();\

        Assert.IsNotNull(testSingletonInjectionClass);
    }
}

I have two questions

1. Is this correct method to get singleton class instance?

 kernel.Get<TestSingletonInjectionClass>()

2. How to get singleton instance class from app code. In test method I create Ninject Kernel and access Get method. How to access ninject kernel form code?

2

2 Answers

5
votes

You have to configure the the class is a singleton:

kernel.Bind<TestSingletonInjectionClass>().ToSelf().InSingletonScope();

In the implementations you get it by passing it to the constructor of the consuming class.

public class Foo
{
    public Foo(TestSingletonInjectionClass testSingletonInjectionClass)
    {
        this.testSingletonInjectionClass = testSingletonInjectionClass;
    }
}
0
votes

As you can read on ninject documentation (https://github.com/ninject/ninject/wiki/Object-Scopes) a "InSingletonScope" creates a "Singleton Style of life", not a traditional singleton. The documentation says:

"Only a single instance of the type will be created, and the same instance will be returned for each subsequent request."

This means you will have only one instance x container. If anyone uses another container, will get another instance.