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



tl;dr
在传统应用程序中,区域性信息存储在HttpContext.Current.Session["culture"]中。我如何在Windsor中引入DI,以便在运行应用程序时仍然在那里获取和设置文化信息,但我可以在测试中模拟它?

完整背景:
我有一些用于本地化的遗留代码,我希望对这些代码进行重构,以实现嘲讽和测试。目前,自定义类Lang基于提供的string keyHttpContext.Current.Session["culture"] as CultureInfo获取本地化字符串。

我最初的想法是简单地使用Windsor注入一个CultureInfo实例,并在运行整个web应用程序时安装它以从与以前相同的位置获取它,但在测试时,我只需注册一个new CultureInfo("en-GB")。这就是我为安装人员想出的:

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")));
    }
}

但现在,当运行应用程序时,我在指示的行上得到一个空引用异常。我怀疑这是因为我试图过早地连接它——容器已初始化,安装程序已在Global.asax.cs中的Application_Start下注册,我不确定届时是否设置了HttpContext.Current.Session(甚至HttpContext.Current(。

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

延迟组件的实例化:

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

最新更新