Search code examples
c#dependency-injectionninjectninject-2

Constructor with Dependencies


What I want is for Ninject to resolve this type of situation:

Class1(IClass2 a, IClass3, b, IClass c, IClass d) : IClass1

Class2() : IClass2

Class3(IClass2 a) : IClass3

So just to explain Class1 has a dependency on IClass2, which is injected in first, the remaining parameters are all of type IClass3 which itself has a dependency on IClass2. What I need is a way to get a new instance of Class1 and make sure that the same instance of IClass2 is used when Ninject resolves the dependencies for the instances of type IClass3.

Hope that makes sense.


Solution

  • You can use ninject Object Scopes.

    Some examples:

    • InSingletonScope() will create one instance of the object for the entire app:

      Bind<IClass2>().To<Class2>().InSingletonScope();
      
    • InThreadScope()will create one instance of the object for every thread:

      Bind<IClass2>().To<Class2>().InThreadScope();
      

    You can find more other scopes in the link above.