非类的依赖注入 [英] Dependency Injection with Non-Classes
问题描述
我对依赖注入有些陌生.我已经为某些类将它们的依赖项作为构造函数中的参数传递给它进行了设置,但是我有一些构造函数采用诸如String
或boolean
之类的基元.显然,如果我要对该类使用依赖注入,则需要将它们从构造函数中删除.
对于这种情况,什么是最佳"实践?使构造函数仅获取依赖项,并为该类所需的所有原语提供setter方法?
我的观察是,在大多数情况下,具有同时具有依赖关系和基元的构造函数的类会破坏此示例为例,其中 I am somewhat new to Dependency Injection. I have set it up for some classes that pass in their dependencies as parameters in the constructor, but I have some constructors that take primitives like For a case like this, what is a "best" practice? Make the constructor just take the dependencies and provide a setter method for all of the primitives that the class requires? My observation is that in most cases, classes that have a constructor that takes both dependencies and primitives, break the Single Responsibility Principle or at least result in a design that is less clean, which leads to container configurations that are more fragile and harder to understand. In most (if not all) cases, those primitives are configuration values, such as connection strings, debug options, and such. There are a few ways you can change your design to solve this:
这篇关于非类的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!NotifyCustomerHandler
采用string
应该已经封装到某种NotificationService
中.
NotifyCustomerHandler
,它可能依赖于INotifyCustomerHandlerConfiguration
.过去,我以前只有一个IMyApplicationConfiguration
接口,其中包含应用程序所需的所有配置值,但得出的结论是,这是一个坏主意.这会破坏接口隔离原则,并且您的单元测试将在可读性和可维护性方面受到影响String
or boolean
. Obviously these need to be removed from the constructor if I am to use Dependency Injection for that class.
NotifyCustomerHandler
takes an string notificationServiceUrl
, while that string
should have been encapsulated into some sort of NotificationService
.NotifyCustomerHandler
, it could take a dependency on an INotifyCustomerHandlerConfiguration
. In the past I used to have a single IMyApplicationConfiguration
interface, with all configuration values the application needed, but I came to the conclusion that this is a bad idea. This breaks the Interface Segregation Principle and your unit tests will start to suffer in terms of readability and maintainability.