Resolver for iOS Dependency Injection: Getting Started

Resolver for iOS Dependency Injection: Getting Started

Dependency Injection, or DI, is essential for creating maintainable and testable apps. While DI has been around for many years, some find it intimidating. It sounds complicated, but it’s simple to implement, especially with tools like Resolver, a Dependency Injection framework for Swift.

[…]

Open Xcode and find NetworkService.swift. As you can see by its only property, NetworkService is dependent on URLSession. You need to hide the details of creating URLSession from NetworkService.

[…]

You need to provide the session for NetworkService. Open AssetService.swift and replace:

[…]

Resolver is a Dependency Injection framework for Swift that supports IoC. The framework is already in your Xcode project via the Swift Package Manager, or SwiftPM. Along with SwiftPM, Resolver also supports CocoaPods and Carthage.

[…]

Now, you’ll register AssetViewModel with an argument. Go to App+Injection.swift. In registerAllServices(), add:

Resolver uses the new callAsFunction feature from Swift 5.2 to immediately get the single passed argument from args.

[…]

Next, still in AssetListView.swift, resolve AssetListViewModel using Service Locator. Replace:

[…]

Next, you need to register AssetListViewModel as a service. Open App+Injection.swift. Then, add the following to registerAllServices():

[…]

You’ll use the Graph scope in your app target. Go to App+Injection.swift. Add the following as the first line in registerAllServices():

[…]

Open App+Injection.swift. Then, update register { NetworkService() } to address the protocol:

[…]

Now, still in Resolver+XCTest.swift, change the default root value in registerMockServices(). It must point to your new mock container:

[…]

Open AssetServiceTests.swift. Then, call registerMockServices at the bottom of setUp():

[…]

You can also read more about calling types as functions in our What’s New in Swift 5.2 article.

[…]