-
Notifications
You must be signed in to change notification settings - Fork 72
Scopes
Ilya Puchka edited this page Apr 18, 2016
·
9 revisions
Dip provides 4 scopes (or life-time strategies) that you can use to register dependencies:
- The
.Prototype
scope will make theDependencyContainer
resolve your type as a new instance every time you callresolve
. It's a default scope. - The
.ObjectGraph
scope is like.Prototype
scope but it will make theDependencyContainer
to reuse resolved instances during one call toresolve
method. When this call returns all resolved insances will be discarded and next call toresolve
will produce new instances. This scope must be used to properly resolve circular dependencies. - The
.Singleton
and.EagerSingleton
scopes will make theDependencyContainer
retain the instance once resolved the first time, and reuse it in the next calls toresolve
during the container lifetime..EagerSingleton
scope makes theDependencyContainer
to resolve dependencies registered with this scope when you callbootstrap
method.
You specify scope when you register dependency:
container.register() { ServiceImp() as Service } //.Prototype is a default
container.register(.ObjectGraph) { ServiceImp() as Service }
container.register(.Singleton) { ServiceImp() as Service }
Note:
.Singleton
and.EagerSingleton
scopes are not the same as singleton pattern. There will be only one instance of the component registered with these scopes per container. But they will be not shared between containers and you will be able to create another instance manually.
Warning: Make sure that components registered with
.ObjectGraph
,.Singleton
or.EagerSingleton
scope are thread-safe or are accessed only from a single thread.