c# - 我如何对我的 Controller 进行单元测试以确保 Windsor 在使用 PerWebRequestLifestyle 时可以解决依赖关系

标签 c# unit-testing castle-windsor

我的应用程序中有以下单元测试:

    [TestMethod]
    public void Windsor_Can_Resolve_HomeController_Dependencies()
    {
        // Setup
        WindsorContainer container = new WindsorContainer();
        container.Install(FromAssembly.Containing<HomeController>());

        // Act
        container.Kernel.Resolve(typeof(HomeController));
    }

这样做的目的是确保我没有任何在访问该 Controller 上的操作之前不会意识到的 windsor 配置问题。问题是我所有的对象注册都注册为 PerWebRequestLifestyle,所以我不会遇到跨 Web 请求共享我的 Entity Framwork 数据上下文的问题(这会在运行多个操作时导致错误)。

但是,每当我运行这个单元测试时,我都会遇到以下异常:

System.InvalidOperationException:HttpContext.Current 为空。 PerWebRequestLifestyle 只能在 ASP.Net 中使用

如何在不改变我的对象注册命令的生活方式的情况下测试这个场景?

最佳答案

我不知道您是否可以在 ASP.NET (MVC) 之外使用 PerWebRequestLifestyle(我认为您不能),但您可以使用 IContributeComponentModelConstruction to modify the lifestyle of the components when they are registered .

这将使您能够(集成)测试容器而无需修改任何安装程序。

关于c# - 我如何对我的 Controller 进行单元测试以确保 Windsor 在使用 PerWebRequestLifestyle 时可以解决依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772497/

相关文章:

c# - 已编译的 dll 正则表达式未找到字段异常

c# - MongoDB InsertMany与BulkWrite

python - nosetest 的奇怪行为

.net - 进入 stub 和 mock

c# - 当 DefaultValueHandling 为 Ignore 时,强制单个 JSON 属性始终序列化

c# - 使用正则表达式屏蔽域电子邮件地址

python - 如何在运行单元测试时摆脱第三方库警告?

c# - 将单例与依赖注入(inject)一起使用(CaSTLe Windsor)

wcf - WCF/CaSTLe 内存泄漏

c# - CaSTLe Windsor PerWebRequest 对象注入(inject) Singleton 对象中,而不在字段中引用它