【发布时间】:2014-03-18 22:33:23
【问题描述】:
我正在阅读 M. Seemann 的书 .NET 中的依赖注入,第 2 章。此处提供源代码:http://www.manning.com/seemann/
在 ComplexCommerce 解决方案、CommerceWebPresentationModel、HomeController 中,我们将存储库传递给构造函数:
public HomeController(ProductRepository repository, CurrencyProvider currencyProvider)
然后将其传递给新创建的服务!
public ViewResult Index()
{
var currencyCode = this.CurrencyProfileService.GetCurrencyCode();
var currency = this.currencyProvider.GetCurrency(currencyCode);
var productService =
new ProductService(this.repository);
但是,在 BasketController 中,我们有一个服务传递给构造函数,BasketRepository 被注入到该构造函数中。
public BasketController(IBasketService basketService,
CurrencyProvider currencyProvider)
据我所知,ProductService 没有实现任何接口,这使得 HomeController 无法测试。
我的问题是:为什么 ProductService 在没有 DI 帮助的情况下被实例化?我错过了什么吗?还是作者遗漏了一些东西(否则在一本非常好的书中!)?
【问题讨论】:
-
继续阅读;我想你最终会到达那里。
-
并非每个依赖项都必须通过构造函数注入,或者根本不注入。见第 22 页。
-
@DavidOsborne 我同意,但在这个例子中不是。感谢您的回复。
标签: unit-testing design-patterns dependency-injection solid-principles