Understanding Ninject mvc 3 boiler plate code
Asked Answered
O

1

9

If you install the nuget Ninject package for mvc, it puts a NinjectWebCommon.cs file in the App_Start folder.

I understand 99% of the stuff in this file apart from this line:

kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);

Full code file here on GitHub

In my mind, it would be better to use:

kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => bootstrapper.Kernel);

As the static instance is already defined at the top of the file, and thus it will get the kernal that has all the mappings built.

After some googling it seems this is also common:

kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => ctx.Kernel);

What is the reasoning behind the way the boilerplate code is the way it is?

Orjonikidze answered 11/6, 2014 at 16:4 Comment(0)
D
0

The binding for

"Func<IKernel>>"

Is used to inject a fresh instance of IKernel into the Bootstrapper.Initialize method.

The idea behind creating a new Bootstrapper, is that the Bootstrapper constructor should construct a fully initialized instance of IKernel. That new instance will be used to replace the old instance of the IKernel.

The assumption appears to be that, when the Initialize method is called, you would want to completely reset the IKernel instance in the Bootstrapper instance, removing any bindings added prior to calling Initialize.

Therefore, if you want to do something other than reset your kernel when the application starts, you should refacter the code in the lambda expression, so that a kernel is passed the Bootstrapper.Initialize with the desired state.

I hope this is helpful.

Dylane answered 15/6, 2014 at 13:1 Comment(2)
Hi Scott, you say its used to inject a fresh instance of IKernel into the Bootstrapper.Initialize method - but it does this by making a new Bootstrapper, would this not in affect cause a stack overflow exception or am I missing something?Orjonikidze
When the bootstrapper is reinstantiated, it won't cause a stack overflow exception, because it's not called in the constructor. The bootstrapper is reinstantiated in the initialize method, after the constructor is called. No stack overflow exception, because there's no recursive construction.Dylane

© 2022 - 2024 — McMap. All rights reserved.