为什么我的Castle Windsor控制器工厂的GetControllerInstance()被调用null值?

sco*_*ttm 12 c# asp.net-mvc castle-windsor

我正在使用Castle Windsor来管理控制器实例(以及其他内容).我的控制器工厂看起来像这样:

public class WindsorControllerFactory : DefaultControllerFactory
    {
        private WindsorContainer _container;

        public WindsorControllerFactory()
        {
            _container = new WindsorContainer(new XmlInterpreter());

            var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where typeof(Controller).IsAssignableFrom(t)
                                  select t;

            foreach (Type t in controllerTypes)
            {
                _container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
            }
        }

        protected override IController GetControllerInstance(Type controllerType)
        {
            return (IController)_container.Resolve(controllerType); // ArgumentNullException is thrown here
        }
Run Code Online (Sandbox Code Playgroud)

当我启动我的ASP.Net MVC应用程序并尝试转到"/"(或其他路径)时,我得到一个ArgumentNullException.我在GetControllerInstance的输入上设置了一个断点,发现它使用我的HomeController调用了一次,然后第二次调用null(这是抛出异常的时候).为什么再次被召唤?

我应该将方法更改为这样的方法:

protected override IController GetControllerInstance(Type controllerType)
{
    if (controllerType == null)
        return null;

    return (IController)_container.Resolve(controllerType);
}
Run Code Online (Sandbox Code Playgroud)

sco*_*ttm 26

事实证明,第二个请求是MVC框架试图找到我包含在Site.Master中的脚本.路径不存在,所以我猜它试图解析一个控制器(匹配/Scripts/sitescripts.js).我把方法改为:

protected override IController GetControllerInstance(Type controllerType)
{
    if (controllerType != null)
    {
       return (IController)_container.Resolve(controllerType);
    }
    else
    {
       return base.GetControllerInstance(controllerType);
    }
}
Run Code Online (Sandbox Code Playgroud)

并抛出了可理解的消息的异常.