2

We have a code something like below.

var xyz = method(); //method() returns an interface say **Interface1**

kernel.Bind<**Interface1**>().ToConstant(xyz);

I saw on stackoverflow at the below link:

Usage of binding to constants and binding to types in scopes with Ninject

Can we use Kernel.Bind<**Interface1**>().To(typeof(xyz)).InSingletonScope() if we want the object creation not at the this point but when call is made.

Vicky
  • 624
  • 2
  • 12
  • 35
  • Use [ToMethod](https://github.com/ninject/Ninject/wiki/Providers,-Factory-Methods-and-the-Activation-Context#factory-methods). – Steven Jun 07 '17 at 06:29

1 Answers1

2
Bind<Interface1>().ToMethod(context => method()).InSingletonScope();
Steven
  • 166,672
  • 24
  • 332
  • 435
  • Thanks. so the difference between kernel.Bind<**Interface1**>().ToConstant(xyz); and the one you gave above is the time when object is created or something else as well – Vicky Jun 07 '17 at 11:50
  • @Vicky: Correct. – Steven Jun 07 '17 at 11:53
  • one more question. what will happen if I remove InSingletonScope() and just keep Bind().ToMethod(context => method()) ? – Vicky Jun 07 '17 at 15:33
  • In that case `method()` will be called over and over again, instead of just once. – Steven Jun 07 '17 at 15:50