为什么我的温莎城堡控制器工厂的 GetControllerInstance() 被调用为空值?

2024-03-19

我正在使用温莎城堡来管理控制器实例(除其他外)。我的控制器工厂如下所示:

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
        }

当我启动 ASP.Net MVC 应用程序并尝试转到“/”(或其他路径)时,我收到 ArgumentNullException。我在 GetControllerInstance 的入口处放置了一个断点,发现它用我的 HomeController 调用了一次,然后用 null 调用了第二次(此时抛出异常)。怎么又被叫了?

我应该将方法更改为如下所示:

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

    return (IController)_container.Resolve(controllerType);
}

事实证明,第二个请求是 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);
    }
}

并且抛出了带有可理解消息的异常。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的温莎城堡控制器工厂的 GetControllerInstance() 被调用为空值? 的相关文章

随机推荐