Swinject icon indicating copy to clipboard operation
Swinject copied to clipboard

Could SwiftUI's @propertyWrapper be an alternative form of injection?

Open drekka opened this issue 6 years ago • 8 comments

Been messing around with various bits of the latest beta and it occurred to be that an implementation of SwiftUI's @propertyWrapper could be used to access a container and inject a property.

Any thoughts?

drekka avatar Jun 27 '19 06:06 drekka

I like the idea. I think it could make usage throughout the code more clear and concise. E.g. @Injected var analytics: AnalyticsService

nathanblamires avatar Jun 29 '19 09:06 nathanblamires

I have been playing with this idea as well, see #421.

Main issue that I see is passing resolver to the property wrapper - I haven't figured out better way than global variable 😞

jakubvano avatar Jul 04 '19 11:07 jakubvano

Haven't tried it, but could the resolver (main Container) be passed via an @Environment reference?

So it would be a requirement to set the container into the environment of the main view, then all propertywrappers can access it.

Honestly don't know if that will work :-)

drekka avatar Jul 05 '19 04:07 drekka

Using a property wrapper would mean having Swinject inject those dependencies as well when doing unit test.

Doing that we would change Swinject from a dependency injection container to a Service Locator.

I would rather wait for annotations being available in Swift.

pjechris avatar Jul 05 '19 13:07 pjechris

@pjechris I agree - apart from implementation issues, this would basically encourage an untestable code, and property wrappers probably aren't the best fit for the DI framework.

However, there is no requirement to use it in the entire codebase.. I could see this as a much more powerful replacement for the SwinjectStoryboard - one rarely unittests the UI layer, and it would enable the injection into other UI objects, not only UIViewController

jakubvano avatar Jul 08 '19 09:07 jakubvano

Looks like this feature of property wrapers is already implemented in latest Xcode-beta, which enables us to get a resolver instance from the enclosing type 🎉

POC implemented here, in action here.

jakubvano avatar Aug 24 '19 16:08 jakubvano

Any updates?

Zeta611 avatar Mar 30 '20 19:03 Zeta611

I'm digging into this to see if we can get it officially released! Also looking at how this could factor into SwiftUI. Stay tuned for more updates here!

mpdifran avatar Jul 08 '21 02:07 mpdifran