Unit testing 为什么一个控制器注入了存储库,而另一个控制器注入了服务

Unit testing 为什么一个控制器注入了存储库,而另一个控制器注入了服务,unit-testing,design-patterns,dependency-injection,solid-principles,Unit Testing,Design Patterns,Dependency Injection,Solid Principles,我正在读m.Seemann的书.NET中的依赖注入,第2章。此处提供的源代码: 在ComplexCommerce解决方案、CommerceWebPresentationModel、HomeController中,我们已将存储库传递给构造函数: public HomeController(ProductRepository repository, CurrencyProvider currencyProvider) 然后将其传递给新创建的服务 public ViewResult Inde

我正在读m.Seemann的书.NET中的依赖注入,第2章。此处提供的源代码:

在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帮助的情况下被实例化?我错过什么了吗?或者这是作者错过的东西(在一本真正的好书中除外!)?

希望能为这件事提供更多的线索

简而言之,它只是一个例子,但不是本书的亮点之一。我通常不会在实际的生产代码库中故意编写这样的代码

然而,我不同意
HomeController
是不稳定的,因为我使用测试驱动开发为这本书编写了整个代码库。您可以下载这本书的代码,并验证它是否包含在测试中。但是,我同意
HomeController
比以前更难进行单元测试


作为记录,我在编码时会犯错误,就像其他人一样…

继续阅读;我想你最终会达到目的的。不是每个依赖项都必须通过构造函数注入,或者根本不注入。见第22页。@DavidOsborne我同意,但在本例中不同意。谢谢你的回复。谢谢你的链接,解释了很多。如果我知道的更好,我就不会读你的书了!我的前两个项目完全是你“做错”例子的复制品。我只是想确定我没有错过什么。我同意你关于测试的看法,但我只是想指出,这种依赖性使得HomeController测试变得脆弱。谢谢你的回复。