Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point to bind Ninject Kernel ToConstant and use InTransientScope?

Tags:

c#

kernel

ninject

I want to bind IServiceProvider to Ninject IKernel implementation. What is the point to use

Bind<IKernel>().ToConstant(this).InTransientScope();

binding from Ninject sources ?

This is the way how Ninject bind IKernel to KernelBase implementation. I can't understand the point. ToConstant binding type set scope to Singleton implicitly. And TransientScope with ToConstant binding type does not give any sense to me.

like image 847
Vladislav Kostenko Avatar asked Jan 16 '15 12:01

Vladislav Kostenko


1 Answers

ToConstant has two primary effects:

  • ninject keeps a strong reference to the "constant" through the whole lifetime of the kernel
  • the scope is configured to Singleton scope.

Now the call to .InTransientScope() after ToConstant changes the scope from Singleton back to transient.

What does this change? "transient" objects will not be disposed by ninject. For Singleton objects, if they're disposable, ninject will dispose them when the kernel is disposed. It's not doing that for "transient" objects.

So if the kernel would be bound .InSingletonScope(), doing kernel.Dispose() would result in another call to kernel.Dispose() - maybe even a Stack Overflow.

like image 101
BatteryBackupUnit Avatar answered Oct 04 '22 21:10

BatteryBackupUnit