使用Castle Windsor在遗留代码中注入HttpContext.Current.Session

时间:2011-07-14 13:19:30

标签: asp.net-mvc-2 session dependency-injection castle-windsor

TL;博士
在旧版应用中,文化信息存储在HttpContext.Current.Session["culture"]中。我如何在这里介绍DI与温莎,所以当运行应用程序仍然获取并设置文化信息,但我可以在我的测试中模拟它?

完整背景:
我有一些用于本地化的遗留代码,我希望重构以启用模拟和测试。目前,自定义类Lang会根据提供的string keyHttpContext.Current.Session["culture"] as CultureInfo提取本地化字符串。

我最初的想法是简单地使用Windsor注入一个CultureInfo实例,然后安装它以便在运行整个Web应用程序时从同一个地方获取它,但是在测试时我只需注册一个{{ 1}}而不是。这就是我为安装人员提出的建议:

new CultureInfo("en-GB")

但是现在运行应用程序时,我在指定的行上得到一个空引用异常。我怀疑这是因为我试图过早地解决这个问题 - 容器已初始化并且安装程序在Global.asax.cs中的public class CultureInfoFromSessionInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( // exception here (see comments below) Component.For<CultureInfo>() .Instance(HttpContext.Current.Session["culture"] as CultureInfo) .LifeStyle.PerWebSession()); } } class EnglishCultureInfoInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<CultureInfo>() .Instance(new CultureInfo("en-GB"))); } } 下注册,我不确定Application_Start(或偶数HttpContext.Current.Session)是由当时设定的。

有没有一种很好的方式来获得我在这里要做的事情?

1 个答案:

答案 0 :(得分:5)

延迟组件的实例化:

container.Register( 
        Component.For<CultureInfo>()
        .UsingFactoryMethod(() => HttpContext.Current.Session["culture"] as CultureInfo)
        .LifeStyle.PerWebSession());