-
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 theDependencyContainerresolve 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 likeUniquescope but it will make theDependencyContainerto reuse resolved instances while resolving an objects graph. When graph is resolved all resolved instances will be discarded and next call toresolvewill produce new instances. This scope must be used to properly resolve circular dependencies. It's a default scope since version 5.0. - The
SingletonandEagerSingletonscopes will make theDependencyContainerretain the instance once resolved the first time, and always reuse it during the container lifetime.EagerSingletonscope makes theDependencyContainerto resolve dependencies registered with this scope when you callbootstrapmethod. Container will release singleton instances when it is reset. - The
WeakSingletonscope 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,WeakSingletonscopes 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,EagerSingletonorWeakSingletonscope are thread-safe or are accessed only from a single thread.