Content deleted Content added
m v2.05b - Bot T20 CW#61 - Fix errors for CW project (Reference before punctuation) |
m →C++: fix typo: wrong type was used for the member variable, code wouldn't compile |
||
(21 intermediate revisions by 15 users not shown) | |||
Line 1:
{{Short description|Software programming technique}}
[[File:DependencyInjectionServiceProvider.png|alt=A diagram of an archetypical dependency injection container for the .NET platform.|thumb|Dependency injection is often used alongside specialized frameworks, known as 'containers', to facilitate program composition.]]
[[File:Dependency injection example app.svg|thumb|PetManager gets injected into PetController and PetRepository gets injected into PetManager]]
In [[software engineering]], '''dependency injection''' is a programming technique in which an [[Object (computer science)|object]] or [[Subroutine|function]] receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to [[separation of concerns|separate the concerns]] of constructing objects and using them, leading to [[Loose coupling|loosely coupled]] programs.<ref>{{Cite web |last=Seemann |first=Mark |title=Dependency Injection is Loose Coupling |url=http://blog.ploeh.dk/2010/04/07/DependencyInjectionisLooseCoupling/ |access-date=2015-07-28 |website=blog.ploeh.dk}}</ref><ref name="MarkSeeman2011P4" /><ref>Niko Schwarz, Mircea Lungu, Oscar Nierstrasz, "Seuss: Decoupling responsibilities from static methods for fine-grained configurability", Journal of Object Technology, volume 11, no. 1 (April 2012), pp. 3:1–23.</ref> The pattern ensures that an object or function that wants to use a given [[Service (systems architecture)|service]] should not have to know how to construct those services. Instead, the receiving "[[Client (computing)|client]]" (object or function) is provided with its dependencies by external code (an "injector"), which it is not aware of.<ref name="HollywoodPrinciple.c2">{{Cite web |title=HollywoodPrinciple |url=http://c2.com/cgi/wiki?HollywoodPrinciple |access-date=2015-07-19 |website=c2.com}}</ref> Dependency injection makes implicit dependencies explicit and helps solve the following problems:<ref>{{cite web |title=The Dependency Injection design pattern – Problem, Solution, and Applicability |url=http://w3sdesign.com/?gr=u01&ugr=proble |access-date=2017-08-12 |website=w3sDesign.com}}</ref>
* How can a [[Class (computer programming)|class]] be independent from the creation of the objects it depends on?
* How can an application
Dependency injection is often used to keep code in-line with the [[dependency inversion principle]].<ref>{{Cite web |last=Erez |first=Guy |date=2022-03-09 |title=Dependency Inversion vs. Dependency Injection |url=https://betterprogramming.pub/straightforward-simple-dependency-inversion-vs-dependency-injection-7d8c0d0ed28e |access-date=2022-12-06 |website=Medium |language=en}}</ref><ref>{{Cite web |last=Mathews |first=Sasha |date=2021-03-25 |title=You are Simply Injecting a Dependency, Thinking that You are Following the Dependency
In [[
Application frameworks often combine dependency injection with [[inversion of control]]. Under inversion of control, the framework first constructs an object (such as a controller), and then passes [[control flow]] to it. With dependency injection, the framework also instantiates the dependencies declared by the application object (often in the constructor method's parameters), and passes the dependencies into the object.<ref>{{cite web |title=Spring IoC Container |url=https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/beans.html |access-date=2023-05-23 |language=en }}</ref>
Dependency injection implements the idea of "inverting control over the implementations of dependencies
== Roles ==
Line 32 ⟶ 33:
=== Interfaces ===
Clients should not know how their dependencies are implemented, only their names and [[Application programming interface|API]]. A service which retrieves [[
=== Injectors ===
The '''injector''', sometimes also called an assembler, container, provider or factory, introduces services to the client.
The role of injectors is to construct and connect complex object graphs, where objects may be both clients and services. The injector itself may be many objects working together, but must not be the client, as this would create a [[circular dependency]].
Because dependency injection separates how objects are constructed from how they are used, it often diminishes the importance of the '''<code>new</code>''' keyword found in most [[Object-oriented programming|object-oriented languages]]. Because the framework handles creating services, the programmer tends to only directly construct [[value object]]s which represents entities in the program's ___domain (such as an <code>Employee</code> object in a business app or an <code>Order</code> object in a shopping app).<ref>{{Cite web |title=To "new" or not to "new"
=== Analogy ===
As an analogy, [[
Cars present a uniform interface through their pedals, steering wheels and other controls. As such, which engine they were 'injected' with on the factory line ceases to matter and drivers can switch between any kind of car as needed.
== Advantages and disadvantages ==
=== Advantages ===
A basic benefit of dependency injection is decreased coupling between classes and their dependencies.<ref>{{Cite web|title=the urban canuk, eh: On Dependency Injection and Violating Encapsulation Concerns|url=http://www.bryancook.net/2011/08/on-dependency-injection-and-violating.html|access-date=2015-07-18|website=www.bryancook.net}}</ref><ref>{{Cite web|title=The Dependency Injection Design Pattern|url=https://msdn.microsoft.com/en-us/library/vstudio/hh323705(v=vs.100).aspx|access-date=2015-07-18|website=msdn.microsoft.com}}</ref>
By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.<ref name="JSR330">{{Cite web|title=The Java Community Process(SM) Program - JSRs: Java Specification Requests - detail JSR# 330|url=https://jcp.org/en/jsr/detail?id=330|access-date=2015-07-18|website=jcp.org}}</ref>
This also results in increased flexibility: a client may act on anything that supports the intrinsic interface the client expects.<ref>{{cite web |url=https://python.astrotech.io/design-patterns/structural/dependency-injection.html |url-status=dead |archive-url=https://web.archive.org/web/20200208005839/http://python.astrotech.io/design-patterns/structural/dependency-injection.html |archive-date=2020-02-08 |title=3.1. Dependency injection — Python 3: from None to Machine Learning}}</ref>
Line 62 ⟶ 63:
Many of dependency injection's benefits are particularly relevant to [[Unit testing|unit-testing]].
For example, dependency injection can be used to externalize a system's configuration details into configuration files, allowing the system to be reconfigured without recompilation. Separate configurations can be written for different situations that require different implementations of components.<ref>{{Cite web|url=http://python-dependency-injector.ets-labs.org/introduction/di_in_python.html|title = Dependency injection and inversion of control in Python — Dependency Injector 4.36.2 documentation}}</ref>
Similarly, because dependency injection does not require any change in code behavior, it can be applied to legacy code as a [[Code refactoring|refactoring]]. This makes clients more independent and are easier to [[Unit testing|unit test]] in isolation, using [[Method stub|stubs]] or [[mock object]]s, that simulate other objects not under test.
This ease of testing is often the first benefit noticed when using dependency injection.<ref>{{Cite web|url=https://visualstudiomagazine.com/articles/2014/07/01/larger-applications.aspx |title = How to Refactor for Dependency Injection, Part 3: Larger Applications }}</ref>
Line 77 ⟶ 78:
== Types of dependency injection ==
There are
* Constructor injection, where dependencies are provided through a client's class [[Constructor (object-oriented programming)|constructor]].
* Method Injection, where dependencies are provided to a method only when required for specific functionality.
* Setter injection, where the client exposes a setter method which accepts the dependency.
* Interface injection, where the dependency's interface provides an injector method that will inject the dependency into any client passed to it.
Line 105 ⟶ 107:
// The dependency is injected through a constructor.
Client(final Service service) {
if (service == null) {
throw new IllegalArgumentException("service must not be null");
Line 112 ⟶ 114:
}
}
</syntaxhighlight>
=== Method Injection ===
Dependencies are passed as arguments to a specific method, allowing them to be used only during that method's execution without maintaining a long-term reference. This approach is particularly useful for temporary dependencies or when different implementations are needed for various method calls.
<syntaxhighlight lang="java">
public class Client {
public void performAction(Service service) {
if (service == null) {
throw new IllegalArgumentException("service must not be null");
}
service.execute();
}
}
</syntaxhighlight>
=== Setter injection ===
By accepting dependencies through a [[setter method]], rather than a constructor, clients can allow injectors to manipulate their dependencies at any time. This offers flexibility, but makes it difficult to ensure that all dependencies are injected and valid before the client is used.
<syntaxhighlight lang="java">
Line 122 ⟶ 138:
// The dependency is injected through a setter method.
public void setService(final Service service) {
if (service == null) {
throw new IllegalArgumentException("service must not be null");
Line 149 ⟶ 165:
@Override
public void setService(final Service service) {
if (service == null) {
throw new IllegalArgumentException("service must not be null");
Line 160 ⟶ 176:
private final Set<ServiceSetter> clients = new HashSet<>();
public void inject(final ServiceSetter client) {
this.clients.add(client);
client.setService(new ExampleService());
Line 166 ⟶ 182:
public void switch() {
for (final Client client : this.clients) {
client.setService(new AnotherExampleService());
}
Line 183 ⟶ 199:
public class Program {
public static void main(final String[] args) {
// Build the service.
final Service service = new ExampleService();
// Inject the service into the client.
final Client client = new Client(service);
// Use the objects.
Line 196 ⟶ 212:
</syntaxhighlight>
Manual construction may be more complex and involve [[Builder pattern|builders]], [[Factory (object-oriented programming)|factories]], or other [[Creational pattern|construction patterns]].
=== Frameworks ===
Line 208 ⟶ 224:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Injector {
public static void main(final String[] args) {
// Details about which concrete service to use are stored in configuration separate from the program itself.
final BeanFactory beanfactory = new ClassPathXmlApplicationContext("Beans.xml");
final Client client = (Client) beanfactory.getBean("client");
System.out.println(client.greet());
}
Line 280 ⟶ 295:
The <code>ng-controller</code> directive triggers the injector to create an instance of the controller and its dependencies.
=== C++ ===
This sample provides an example of constructor injection in [[C++]].
<syntaxhighlight lang="c++">
import std;
class DatabaseConnection {
public:
void connect() {
std::println("Connecting to database...");
}
};
class DatabaseService {
private:
DatabaseConnection& dbConn;
public:
explicit DatabaseService(DatabaseConnection& db):
dbConn{db} {}
void execute() {
dbConn.connect();
std::println("Executing database service...");
}
};
int main(int argc, char* argv[]) {
DatabaseConnection db;
DatabaseService sv(db);
sv.execute();
}
</syntaxhighlight>
This sample provides an example of interface injection in C++.
<syntaxhighlight lang="c++">
import std;
enum class DatabaseConnectionError {
NoConnection,
// more errors here
};
class IConnection {
public:
virtual void connect() = 0;
virtual ~IConnection() = default;
};
class DatabaseConnection: public IConnection {
public:
DatabaseConnection() = default;
void connect() override {
std::println("Connecting to database...");
}
};
class DatabaseService {
private:
std::shared_ptr<IConnection> conn;
public:
DatabaseService() = default;
void setConnection(std::shared_ptr<IConnection> nextConn) noexcept {
conn = nextConn;
}
std::expected<void, DatabaseConnectionError> execute() {
if (conn) {
conn->connect();
std::println("Executing database service...");
} else {
return std::unexpected(DatabaseConnectionError::NoConnection);
}
}
};
int main(int argc, char* argv[]) {
std::shared_ptr<DatabaseConnection> db = std::make_shared<DatabaseConnection>();
DatabaseService sv;
sv.setConnection(db);
sv.execute();
}
</syntaxhighlight>
=== C# ===
This sample provides an example of constructor injection in [[
<syntaxhighlight lang="csharp">
using System;
Line 289 ⟶ 389:
// Our client will only know about this interface, not which specific gamepad it is using.
interface
{
string GetGamePadName();
void SetVibrationPower(float power);
}
Line 296 ⟶ 397:
// The following services provide concrete implementations of the above interface.
class
{
float vibrationPower = 1.0f;
public string
public void SetVibrationPower(float power) => this.vibrationPower = Math.Clamp(power, 0.0f, 1.0f);
}
class PlayStationJoystick : IGamePadFunctionality
{
float vibratingPower = 100.0f;
public string
public void SetVibrationPower(float power) => this.vibratingPower = Math.Clamp(power * 100.0f, 0.0f, 100.0f);
}
class SteamController :
{
double vibrating = 1.0;
public string
public void SetVibrationPower(float power) => this.vibrating = Convert.ToDouble(Math.Clamp(power, 0.0f, 1.0f));
Line 321 ⟶ 425:
// This class is the client which receives a service.
class
{
IGamePadFunctionality gamePadFunctionality;
// The service is injected through the constructor and stored in the above field.
public
public void Showcase()
{
// The injected service is used.
Console.WriteLine(message);
}
Line 336 ⟶ 442:
class Program {
static void Main(string[] args)
{
SteamController steamController = new SteamController();
// We could have also passed in an XboxController,
// The gamepad doesn't know what it's using and doesn't need to.
gamepad.Showcase();
Line 349 ⟶ 456:
=== Go ===
Go does not support classes and usually dependency injection is either abstracted by a dedicated library that utilizes [[Reflective programming|reflection]] or [[Generic programming|generics]] (the latter being supported since Go 1.18
First, pass the necessary dependencies to a router and then from the router to the controllers:
Line 402 ⟶ 509:
</syntaxhighlight>
Then, you can access the private fields of the [[Record (computer science)|struct]] in any method that is
<syntaxhighlight lang="go">
package users
Line 468 ⟶ 575:
User struct {
Name string
JoinedAt time.Time
Email string
}
)
Line 496 ⟶ 603:
* [[Factory pattern]]
* [[Inversion of control]]
* [[Mock trainwreck]]
* [[Plug-in (computing)]]
* [[Strategy pattern]]
* [[Service locator pattern]]
* [[Parameter (computer programming)]]
Line 514 ⟶ 621:
* [http://martinfowler.com/articles/injection.html Martin Fowler's original article that introduced the term Dependency Injection]
* [http://martinfowler.com/eaaCatalog/plugin.html P of EAA: Plugin]
*
* [http://tutorials.jenkov.com/dependency-injection/index.html What is Dependency Injection?] - An alternative explanation - Jakob Jenkov
* [http://www.developer.com/net/net/article.php/3636501 Writing More Testable Code with Dependency Injection -- Developer.com, October 2006] {{Webarchive|url=https://web.archive.org/web/20080311121626/http://www.developer.com/net/net/article.php/3636501 |date=2008-03-11 }}
|