What is a scope"In computer programming, a scope is the context within a computer program in which a variable name or other identifier is valid and can be used, or within which a declaration has effect. Outside of the scope of a variable name, the variable's value may still be stored, and may even be accessible in some way, but the name does not refer to it; that is, the name is not bound to the variable's storage" (Wikipedia).
In one sentence
Scope is a fixed duration of time or method calls in which an object exists.
What resolution scope means?In term of Dependency Injection, the scope defines the life-cycle and visibility of instances.
A scope determines when a new instance of registered type with that scope is created and when an existing instance with that scope is destroyed. An instance of a scoped type is bound to the scope and is shared during the execution in the context of the scope.
Common resolution scopes
- No Scope (Transient, Prototype) : A new instance is created each time you request
- Singleton (Container): The same instance is used each time you request it from this container
- Thread: An instance is created for each thread
Common resolution scopes for web applications
- RequestScoped: Scopes a type definition to the life-cycle of a single HTTP request; that is each and every HTTP request will have its own instance of a single type definition.
- SessionScoped: Scopes a single type definition to the life-cycle of a HTTP Session.
- ApplicationScoped: Scopes a single type definition to the life-cycle of a global HTTP Session (and usually binds to ApplicationContext).
Why resolution scope?Using resolution scope has the following benefits:
- It implicitly separates state by context (for example, two HTTP requests imply different contexts).
- It reduces the necessity for state-aware application logic (which makes code much easier to test and reason about).
How to define a custom resolution scopeSometimes, you can not find what you are looking in your selected DI framework. However, some of DI frameworks let you to extend built-in scopes or base classes to define your own custom scope; If not then you need to implement the custom scope yourself.
At the following, you can find out how to define a custom resolution scope in Unity, and use it wherever that you like.
To do that a base class named CustomScope has been defined. Any custom scope that you might use in the application inherits from CustomScope. Following that, a sample code utilizing CustomScope has been demonstrated.
ICustomScope and CustomScope definition
CustomScope usage sample code