Dependency icon indicating copy to clipboard operation
Dependency copied to clipboard

Injecting objects

Open AdieOlami opened this issue 3 years ago • 2 comments

Hi, I'm just wondering how you would inject parameters into a service.

Parameters like string, bool, int etc.

AdieOlami avatar Oct 26 '22 15:10 AdieOlami

When you're setting the dependency, you can just pass your arguments via the initialiser, e.g.

DependencyValues[\.userService] = MockUserService(myParameter1: 0, myParameter2: true)

Does this help?

chFlorian avatar Oct 26 '22 16:10 chFlorian

This is you passing static values. Example

if the parameters change based on scenario probably it is a Codable or Equatable type rather than just String or Bool.

do you just create your key like this or how do you handle that

private struct UserServiceKey: DependencyKey { static var currentValue: UserService = MyUserService(model: SomeModel(name: "abc")) }

extension DependencyValues { var userService: UserService { get { Self[UserServiceKey.self] } set { Self[UserServiceKey.self] = newValue } } }

AdieOlami avatar Oct 30 '22 05:10 AdieOlami