-
Notifications
You must be signed in to change notification settings - Fork 72
Scopes
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
(exPrototype
) scope will make theDependencyContainer
resolve your type as a new instance every time you callresolve
. It's a default scope in versions prior to 5.0. - The
Shared
(exObjectGraph
) scope is likeUnique
scope but it will make theDependencyContainer
to reuse resolved instances while resolving an objects graph. When graph is resolved all resolved instances will be discarded and next call toresolve
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
andEagerSingleton
scopes will make theDependencyContainer
retain the instance once resolved the first time, and always reuse it during the container lifetime.EagerSingleton
scope makes theDependencyContainer
to resolve dependencies registered with this scope when you callbootstrap
method. Container will release singleton instances when it is reset. - The
WeakSingleton
scope is the same scope as aSingleton
, 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
orWeakSingleton
scope are thread-safe or are accessed only from a single thread.