hmlongco / Resolver

Swift Ultralight Dependency Injection / Service Locator framework
MIT License
2.14k stars 188 forks source link

args in Injected Property #115

Closed firatyenidunya closed 3 years ago

firatyenidunya commented 3 years ago

Hi, I'm working on Resolver lately and honestly it's a great work! Thank you so much for this great contribution to swift community.

But also I have a question about args in Injected property. Is there a special reason to preventing passing args to Injected and WeakInjected properties? I just want to pass args to them but it seems like I have to use LazyInjected.

If there are no concerns and if you let me know about it, I can happily contribute to add this feature for Injected and LazyInjected.

hmlongco commented 3 years ago

Glad you like Resolver. (And now that the buttering up is done...) ;)

Any properties of a class or struct are initialized when the object is instantiated. This holds just as true for property wrappers as it does for strings and ints. As such, by the time you're able to access them in order to set an argument they've already initialized (resolved). You're too late.

The only solution if you absolutely need to pass an argument to the factory is to use lazy injection. That way you can set the arguments it will pass to the factory when resolving the type. (Assumes, of course, you set the property before you first access the resolved object.)

Also note that lazy injectors are mutating. This means they can't be used on certain types of structs (like SwiftUI Views).

This also carries the implication that most objects require two-stage initialization. That, however, is mitigated somewhat since you also tend to hit such objects on a lifecycle event (viewDidLoad, viewWillAppear, etc.) and you need that second stage call anyway.

firatyenidunya commented 3 years ago

Thank you for explanation. I didn't think in that way, it's clear now.