Asp.net Mvc中MVCContrib中无法使用Castle的解决方案
        在使用Asp.net Mvc MVCContrib中的Castle有时会出现No component for key HomeController was found这样的错误
        在看了园子里的《Asp.net Mvc中MVCContrib中无法使用Castle的发解决方案 》这篇文章之后,按文章的方法修改了代码,修改方法如下:
下载MvcContrib源代码,更改MvcContrib.Castle的WindsorControllerFactory.cs中的34行CreateController方法为:
{
controllerName = controllerName + "Controller"; //更改了这里
IWindsorContainer container = GetContainer(context);
return (IController)container.Resolve(controllerName);
}
这个更改方法可能仅限于MVCContrib 0.0.1.91
        这样修改使得MvcContrib.Samples.NVelocityViewFactory这个例子可以正常运行,但另一个例子MvcContrib.Samples.WindsorControllerFactory却出现类似的问题。
        因此在MVCContrib的Google论坛里提出了疑问,最后得到了解释:
        由于组件名在Windsor是区分大小写的,而ASP.NET MVC里的Controller却是不区分的。如果按上面的代码修改,mysite.com/Home/index 这个地址会正常工作,而mysite.com/home/index将会报错 ,因为home是小写。
        因此把组件名强制注册为小写是目前的解决方案,就像修改之前的代码那样:   
{
controllerName = controllerName.ToLower() + "controller"; //更改了这里
IWindsorContainer container = GetContainer(context);
return (IController)container.Resolve(controllerName);
}
不过既然不用修改源代码,那MvcContrib.Samples.NVelocityViewFactory这个例子还是会出错啊,没错,这个例子是存在BUG,不过修改起来很简单。只需修改Global.asax.cs文件的一行代码:
 protected virtual void InitializeWindsor()
protected virtual void InitializeWindsor() {
        { if (_container == null)
            if (_container == null) {
            { _container = new WindsorContainer();
                _container = new WindsorContainer();
 // Add our singleton NVelocityViewFactory
                // Add our singleton NVelocityViewFactory _container.AddComponent("ViewFactory", typeof(IViewEngine), typeof(Castle.NVelocityViewFactory));
                _container.AddComponent("ViewFactory", typeof(IViewEngine), typeof(Castle.NVelocityViewFactory));
 Type[] assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
                Type[] assemblyTypes = Assembly.GetExecutingAssembly().GetTypes(); 
                 foreach (Type type in assemblyTypes)
                foreach (Type type in assemblyTypes) {
                { if (typeof(IController).IsAssignableFrom(type))
                    if (typeof(IController).IsAssignableFrom(type)) {
                    { //_container.AddComponentWithLifestyle(type.Name, type, LifestyleType.Transient); //修改前
                        //_container.AddComponentWithLifestyle(type.Name, type, LifestyleType.Transient); //修改前 _container.AddComponentWithLifestyle(type.Name.ToLower(), type, LifestyleType.Transient); //修改后
                        _container.AddComponentWithLifestyle(type.Name.ToLower(), type, LifestyleType.Transient); //修改后 ControllerBuilder.Current.SetControllerFactory( typeof(WindsorControllerFactory));
                        ControllerBuilder.Current.SetControllerFactory( typeof(WindsorControllerFactory)); }
                    } }
                } }
            } }
        }
     
      
 
        
 
             
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号