What is the best way to reset Ninject's IKernel container in an MVC app?
Basically in my Global.asax
code I have the following IKernel
property for Ninject setup like this (Also taking advantage of Microsoft.Practices.ServiceLocation). This Container is automatically called upon once it seems on the CreateKernel()
override:
protected override IKernel CreateKernel()
{
return Container;
}
and my container property:
static IKernel _container;
public static IKernel Container
{
get
{
if (_container == null)
{
_containe开发者_如何转开发r = new StandardKernel();
_container.Load(new SiteModule(_container));
ServiceLocator.SetLocatorProvider(() => _container.Get<IServiceLocator>());
}
return _container;
}
}
As you can see I am loading simply one module defining a list of my interface<->service bindings, which shouldn't be important to this problem however, but my problem being - no matter how hard I seem to try, I cannot get my _container
null again once it has been initially instantiated when I restart my MVC website. From editing and re-saving the Web.config file (good old trick) through to flushing the app pool or even restarting IIS(!), my container apparently still exists. I really don't understand how this can be the case. I know on my initial loads _container
is null and SiteModule
does load correctly.
This is a problem of course because I now wish to add some new bindings for newly created services and the container is never returning to null :P
FYI. Even moving my breakpoint into the container null test doesn't appear to get this going, don't ask me how this doesn't fix the issue, but I know the inside of that if should be valid, because on initial load there are no errors, everything maps up fine.
Thanks guys, if you feel you need to see SiteModule()
let me know and I can extend this post with the code.
Have you tried restarting your web server? I realize this might not be an option in production, but it should get you through the development phase (if it works).
If I am not mistaken, CreateKernel()
is only called once during Application_Start()
(view source) so, unless you are using 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's implementation.
精彩评论