Castle/Windsor新手,请耐心等待.
我目前正在使用框架System.Web.Mvc.Extensibility,并在其启动代码中,它注册了HttpContextBase,如下所示:
container.Register(Component.For().LifeStyle.Transient.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));
我想要做的是改变行为并将httpContextBase的生活方式改为PerWebRequest.
所以我将代码更改为以下内容:
container.Register(Component.For().LifeStyle.PerWebRequest.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));
但是,当我这样做时,我收到以下错误:
System.Configuration.ConfigurationErrorsException: Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule Add '' to the section on your web.config
这是我做下
和
,但是,我仍然得到同样的错误.任何提示?
提前致谢.
更新
每个请求添加了代码块
在system.web.mvc.extensibility框架中,有一个名为extendedMvcApplication的类,它继承自HttpApplication,在Application_start方法中,它调用BootStrapper.Execute().此方法的实现如下:
public void Execute() { bool shouldSkip = false; foreach (IBootstrapperTask task in ServiceLocator.GetAllInstances().OrderBy(task => task.Order)) { if (shouldSkip) { shouldSkip = false; continue; } TaskContinuation continuation = task.Execute(ServiceLocator); if (continuation == TaskContinuation.Break) { break; } shouldSkip = continuation == TaskContinuation.Skip; } }
如您所见,它循环遍历IBootStrapperTask列表并尝试执行它们.碰巧我有一个任务在我的mvc应用程序中注册路由:
public class RegisterRoutes : RegisterRoutesBase { private HttpContextBase contextBase; protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { contextBase = serviceLocator.GetInstance(); return base.ExecuteCore(serviceLocator); } protected override void Register(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" }); routes.IgnoreRoute("{*robotstxt}", new { robotstxt = @"(.*/)?robots.txt(/.*)?" }); XmlRouting.SetAppRoutes(routes, contextBase.Server.MapPath("~/Configuration/Routes.xml")); } }
你可以看到我需要getInstance(解析)一个httpcontextbase对象,这样我就可以得到一个xml文件的服务器路径.
在撰写本文时,PerWebRequest生活方式不支持在Application_Start()中进行解析.
请参阅问题描述和讨论:
http://support.castleproject.org/projects/IOC/issues/view/IOC-ISSUE-166
http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e
这种特殊情况的解决方法:
注册RegisterRoutes
为实例,显式地将当前上下文作为构造函数参数传递,例如:
container.Register(Component.For() .Instance(new RegisterRoutes(Context)));
用HostingEnvironment.MapPath
而不是contextBase.Server.MapPath
.想让它变得模糊吗?通过简单的界面使用它,例如:
interface IServerMapPath { string MapPath(string virtualPath); } class ServerMapPath: IServerMapPath { public string MapPath(string virtualPath) { return HostingEnvironment.MapPath(virtualPath); } } container.AddComponent();
然后注入IServerMapPath
你的RegisterRoutes
.