Dependency Injection is a client/service model, where the client object is dependent on a service object passed to the client as part of its state. The code passing the service object is called the injector, and determines what service the client will use. The client does not call the injector code. The injector builds or finds the services, then passes them into the client, which may also be created by the injector.
Dependency Injection separates construction and use of objects. The pattern requires the service object be passed to the client, instead of having the client build or find the service. It is a form of inversion of control, where the client doesn't need to know about the injector, how to construct the services it needs, or even which services it uses. The client only needs to know about the service interfaces defining how the service is used.
Service: Any object that can be used
e.g. an electric, gas, hybrid, or diesel vehicle
Client: Any object that uses another object
e.g. a driver who uses the vehicle regardless of propulsion method
Interface: Defines the types of dependencies the client expects. The client only knows the interface name and API.
e.g. automatic transmission, ensuring the driver does not have to understand engine details like gears
Injector: Introduces the services to the client, often also constructing the client
e.g. the car purchaser, who decided which kind of car to buy
Setter Injection: Client provides a setter method for the dependency
- Configurability: The client's behavior is fixed, and can act on anything that supports the interface it expects
- Allows separate configuration files for situations requiring different implementations of components (including testing)
- Independent clients are easier to unit test in isolation using stubs or mock objects
DISADVANTAGES:
- Can increase difficulty in reading and writing code by separating behavior from construction
- Hinders IDE automation like "find references" and "show call hierarchy" due to reflection or dynamic programming implementation
- Requires more upfront development to ask something be injected, then ensure it has been injected
- Can encourage dependence on a dependency injection framework
------------------------------------------------------------------------------------------
No comments:
Post a Comment