在MVC应用程序中重置Ninject的IKernel容器的最佳方法是什么?

时间:2010-05-20 12:31:26

标签: .net asp.net-mvc-2 dependency-injection ninject ninject-2

基本上在我的Global.asax代码中,我为Ninject设置提供了以下IKernel属性(同样利用了Microsoft.Practices.ServiceLocation)。一旦它出现在CreateKernel()覆盖:

,就会自动调用此容器
protected override IKernel CreateKernel()
        {
            return Container;
        }

和我的容器属性:

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;
            }
        }

正如您所看到的,我只加载了一个模块,用于定义我的界面列表&lt; - &gt;服务绑定,但这不应该对此问题很重要,但我的问题是 - 无论我多么难以尝试,当我重新启动MVC网站时,一旦最初实例化,我再也无法获得_ container null。从编辑和重新保存Web.config文件(好老技巧)到刷新应用程序池甚至重新启动IIS(!),我的容器显然仍然存在。我真的不明白这是怎么回事。我知道我的初始加载_container为空,SiteModule确实正确加载。

这当然是个问题,因为我现在希望为新创建的服务添加一些新的绑定,容器永远不会返回null:P

FYI。即使将我的断点移动到容器null测试中似乎也没有这样做,不要问我这是怎么解决这个问题的,但是我知道里面的内容应该是有效的,因为在初始加载时有没有错误,一切都很好。

谢谢大家,如果您觉得需要SiteModule()让我知道,我可以使用代码扩展这篇文章。

2 个答案:

答案 0 :(得分:0)

您是否尝试重新启动网络服务器?我意识到这可能不是生产中的一个选项,但它应该让你完成开发阶段(如果它有效)。

答案 1 :(得分:0)

如果我没有记错,CreateKernel()只在Application_Start()view source)期间被调用一次,所以,除非您在其他地方使用Container,否则缓存有任何好处它?

你尝试过这样的事吗?

protected override IKernel CreateKernel()
{
    IKernel kernel = new StandardKernel();

    // Do your Load() and ServiceLocator stuff here

    return kernel;
}

作为参考,Ninject网站的implementation