-
Notifications
You must be signed in to change notification settings - Fork 73
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
.Prototypescope will make theDependencyContainerresolve your type as a new instance every time you callresolve. It's a default scope. - The
.ObjectGraphscope is like.Prototypescope but it will make theDependencyContainerto reuse resolved instances during one call toresolvemethod. When this call returns all resolved insances will be discarded and next call toresolvewill produce new instances. This scope must be used to properly resolve circular dependencies. - The
.Singletonand.EagerSingletonscopes will make theDependencyContainerretain the instance once resolved the first time, and reuse it in the next calls toresolveduring the container lifetime..EagerSingletonscope makes theDependencyContainerto resolve dependencies registered with this scope when you callbootstrapmethod.
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:
.Singletonand.EagerSingletonscopes 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,.Singletonor.EagerSingletonscope are thread-safe or are used only in single thread.