In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service)). An injection is the passing of a dependency to a dependent object (a client)) that would use it.

The service is made part of the client’s state).[1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. - Wikipedia.

TL;DR.

Initializer injection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protocol Serializer {
func serialize(data: Any) -> Data?
}

class RequestSerializer: Serializer {
func serialize(data: Any) -> Data? {
return nil
}
}

class DataManager {
var serializer: Serializer?

init(serializer: Serializer) {
self.serializer = serializer
}
}

let serializer = RequestSerializer()
// DI
let dataManager = DataManager(serializer: serializer)

Property injection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
protocol Serializer {
func serialize(data: Any) -> Data?
}

class RequestSerializer: Serializer {
func serialize(data: Any) -> Data? {
return nil
}
}

class DataManager {
var serializer: Serializer?
}

let dataManager = DataManager()

// DI
dataManager.serializer = RequestSerializer()

Method Injection

1
2
3
4
5
6
7
8
protocol Request {}
protocol Serializer {}

class DataManager {
func serializeRequest(_ request: Request, with serializer: Serializer) -> Data? {
return nil
}
}