Skip to content
Ilya Puchka edited this page Oct 27, 2016 · 9 revisions

Dip provides 4 scopes (or life-time strategies) that you can use to register dependencies:

  • The Unique (ex Prototype) scope will make the DependencyContainer resolve your type as a new instance every time you call resolve. It's a default scope in versions prior to 5.0.
  • The Shared (ex ObjectGraph) scope is like Unique scope but it will make the DependencyContainer to reuse resolved instances while resolving an objects graph. When graph is resolved all resolved instances will be discarded and next call to resolve will produce new instances. This scope must be used to properly resolve circular dependencies. It's a default scope since version 5.0.
  • The Singleton and EagerSingleton scopes will make the DependencyContainer retain the instance once resolved the first time, and always reuse it during the container lifetime. EagerSingleton scope makes the DependencyContainer to resolve dependencies registered with this scope when you call bootstrap method. Container will release singleton instances when it is reset.
  • The WeakSingleton scope is the same scope as a Singleton, but container stores week reference to the resolved instance. While a strong reference to the resolved instance exists resolve will return the same instance. After the resolved instance is deallocated next resolve will produce a new instance.

You specify scope when you register dependency:

container.register() { ServiceImp() as Service } //.Shared is a default
container.register(.Unique) { ServiceImp() as Service }
container.register(.Singleton) { ServiceImp() as Service }

Note: Singleton, EagerSingleton, WeakSingleton scopes are not the same as Singleton pattern. There will be only one resolved instance of the component registered with these scopes per container. But they will be not shared between containers (until they collaborate) and you will be able to create another instance manually.

Warning: Make sure that components registered with Shared, Singleton, EagerSingleton or WeakSingleton scope are thread-safe or are accessed only from a single thread.