What is the best way to reset Ninject IKernel container in MVC application?
Basically in my code Global.asax
, I have the following property IKernel
to customize Ninject like this (also using Microsoft.Practices.ServiceLocation). This container is automatically called after it looks on the override CreateKernel()
:
protected override IKernel CreateKernel()
{
return Container;
}
and my container property:
static IKernel _container;
public static IKernel Container
{
get
{
if (_container == null)
{
_container = new StandardKernel();
_container.Load(new SiteModule(_container));
ServiceLocator.SetLocatorProvider(() => _container.Get<IServiceLocator>());
}
return _container;
}
}
As you can see, I am only loading one module, which defines the list of bindings to the interface and lt; -> which shouldn't be important for this problem, but my problem is no matter how hard I try, I can't get my _ container
null again when it was originally created when I reload my MVC website. From editing and re-saving the Web.config file (old old trick) to flush the application pool, or even restart IIS (!), My container apparently still exists. I really don't understand how this could be. I know that on my initial loads _container
it is null and SiteModule
actually loads.
This is a problem, of course, because now I want to add new bindings for newly created services, and the container never reverts to null: P
FYI. Even moving my breakpoint to the container test doesn't seem like this, don't ask me how it doesn't fix the problem, but I know that inside this it should really be because there are no errors on boot, everything displays fine.
Thanks guys, if you feel like you need to see SiteModule()
, let me know and I can extend this post with code.
a source to share
If I'm not mistaken, CreateKernel()
only called once at a time Application_Start()
( view source ), so if you don't use Container
elsewhere, is there any benefit to caching it?
Have you tried something like this?
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel();
// Do your Load() and ServiceLocator stuff here
return kernel;
}
For reference, the Ninject website is an implementation .
a source to share