hmlongco / Resolver

Swift Ultralight Dependency Injection / Service Locator framework
MIT License
2.15k stars 190 forks source link

Update Injection.md #33

Closed ultraon closed 4 years ago

ultraon commented 4 years ago

I've found the issue with an example of the Method Injection approach. So, it seems to me, I've fixed it.

ultraon commented 4 years ago

BTW, this is amazing article https://medium.com/better-programming/modern-dependency-injection-in-swift-952286b308be

I'm from World of DI Dagger 2, and I have been searching for a DI library for Swift projects.

ultraon commented 4 years ago

I also consider using a mixed approach: Annotation Injection + convenient constructor with all the dependencies. In my point of view, the best benefit of the Annotation Injection is the conciseness of using DI, and the best benefit of adding dependencies via a constructor is a clean code and flexibility in building the object/instance, and I'm wondering, could I still use the convenient constructor along Injected annotations for each property.

I would use a class constructor without DI lib in unit tests, and when I use DI, it would work with the Annotation Injection.

hmlongco commented 4 years ago

If you use Injected all property values will be initialized before your init function is called. So basically you'd be assigning new values to values already initialized.

As mentioned in the article, if I'm doing annotations I tend to forgo writing the full initializer. It's extra code that's not need and IMHO extra boilerplate code is a breeding ground for bugs.

If you really want the initializer, look at using LazyInjected. That way dependencies won't be resolved until the properties are accessed, and they also won't be resolved if you've already provided a value via the initializer.

ultraon commented 4 years ago

If you use Injected all property values will be initialized before your init function is called. So basically you'd be assigning new values to values already initialized.

As mentioned in the article, if I'm doing annotations I tend to forgo writing the full initializer. It's extra code that's not need and IMHO extra boilerplate code is a breeding ground for bugs.

If you really want the initializer, look at using LazyInjected. That way dependencies won't be resolved until the properties are accessed, and they also won't be resolved if you've already provided a value via the initializer.

Looks like @LazyInjected fits well here.