swiftdependency-injectionobserver-patternswinject

Using SwInject in conjunction with a central observer pattern


I am using SWInject to maintain dependencies in my app, and the Coordinator pattern to manage logic and dependencies.

Can the SWInject be used in conjunction with a centralized push notification framework with multiple observers in different parts of the app?

Typically, i do that with a Singleton class, but doing that seems to defeat e purpose of using a dependency injection pattern.


Solution

  • DI in genaral tries to separate "how do I use the dependency" from "how do I obtain the dependecy". In most cases, latter should not be part of an object's knowledge.

    In your case, fact that notification center which object uses to broadacst / receive stuff is a singleton, should be irrelevant to how you implement given object.

    DI approach is to pass it as a dependency, and let somebody else worry about who else might be using the same instance. Sure, on the background it might still be a singleton, but you can change this fact when needed (e.g. testing) without changing anything about objects that use it.