【发布时间】:2015-04-17 01:19:15
【问题描述】:
我正在关注简单注射器文档网站上的文档。
https://simpleinjector.readthedocs.org/en/latest/diagnostics.html
var container = new Container();
container.RegisterWebApiControllers(config);
container.Verify();
var results = Analyzer.Analyze(container);
results.Should()
.HaveCount(0, String.Join( Environment.NewLine, results.Select(x => x.Description)));
但是,当我运行测试时,出现以下错误
Xunit.Sdk.AssertException:
Expected collection to contain 0 item(s) because
MyController is registered as transient, but implements IDisposable.,
but found 1.
我不确定如何设置控制器的范围,因为方法 container.RegisterWebApiControllers(config) 是 webapi 包的一部分并且没有任何重载。如何将这些设置为每个 Web 请求?在其他地方我会这样做container.Register<IPinger, Pinger>(lifestyle);,但似乎我应该使用打包的辅助方法
添加此行以过滤掉不需要的假阴性
results = results.Where(x =>
!(x.ServiceType.BaseType == typeof (ApiController) &&
x.Description.Contains("IDisposable"))
).ToArray();
【问题讨论】:
-
为什么要编写测试来检查 DI 配置?在不运行应用程序的情况下几乎不可能检查 DI 配置是否有效,实际上,Verify 方法本身并不是很有用:blog.ploeh.dk/2011/12/21/TestingContainerConfigurations,即使根据您提供的文档链接也是如此。
-
很公平,也许应该从文档中删除它?
-
我不同意 NightOwl 和 Mark 的文章。尽管可能无法获得 100% 的确定性,但是当您关注 certain rules 时,验证和诊断您的容器将为您提供良好的确定性。在与开发人员团队合作时,我认为验证和诊断您的 DI 配置几乎是一项要求。
标签: c# ioc-container simple-injector