Michael Long
2 min readApr 9, 2021

--

Congratulations. You now have the core of a modern, type-inference based dependency-injection system that uses property wrappers. Kind of like Resolver.

https://github.com/hmlongco/Resolver

Your approach is pretty clean, but it has a couple of fairly large issues at the moment.

One is that your current technique requires you to register an actual instance of the service you want to resolve. In a small app with only a few instances that might not be an issue, but in a larger app that's a lot of up-front overhead.

Bigger still is the fact that you're resolving each and every service to the same instance. In effect, you've just made each and every one a shared singleton. That's behavior you might want for a shared network service but not for a view controller that probably wants a new view model each and every time it's shown.

Your current approach is also very order-specific in how it requires the user to structure their registrations in a particular sequence. If A has a dependency on B, then you have to register B first because you can't make an A without it.

A lot of these issue can be resolved [sic] by simply registering a factory instead of the actual instance, where the "factory" is just a closure that returns a new instance of the object each time it's resolved.

But then you're missing times when you might want shared behavior, or singletons, or objects cached for a certain period (say for a given user login). What dependency injection systems call scope.

Of course, once you start adding things like that your complexity increases proportionally and then you start hitting thread safety and locking issues, etc..

You're also missing out on resolving optionals, namespaces, separate containers, argument passing, and so on.

I guess what I'm saying is that there's a reason some third-party libraries exist, as a lot of simple solutions can increase in complexity extremely quickly. Take it from me. I know. ;)

Enjoying your articles. Keep it up.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (1)