Why does UseNinjectMiddleware take a lambda instead of a container instance?
Is it OK to do this?
var container = CreateKernel();
app.UseNinjectMiddleware(() => container);
instead of this:
app.UseNinjectMiddleware(() => CreateKernel);
My container instance in the first snippet is used to resolve dependencies in another part of my app. Does the Ninject Middleware need to be able to create it's own instances which it can modify, muck-around with and re-create at will? If not, I would like to avoid building the dependency tree more than once, hence why I'm wondering if it's OK for the lambda to just return the instance.
There are a couple of things to note:
The
OwinBootstrappercomponent will load any definedNinjectModule's after calling the passed inFunc<IKernel>so you need to take care that you do not load anything twice. see hereThe
Bootstrappercomponent callsDisposeonIKernelso you will need to be sure you do not attempt to access the instance after a shutdown has been initiated. see hereYou can almost get to the underlying Kernel right after it has been created, maybe you would prefer to raise a PR to make it available?
Currently
OwinAppBuilderExtensionsdefineswhich it uses to store the run-time instance of
OwinBootstrapperOwinBootstrapperholds a private reference to the run-time instance of theBootstrappercomponent and theBootstrapperinstance in turn exposes a reference to the run-time instance ofIKernelSo a little PR adding
to
OwinBootstrappercould make the underlyingIKernelavailable to your code viaapp.Propertiesafter the call toapp.UseNinjectMiddleware(() => container);.