Creating
The Scope API uses a builder pattern allowing you to inject any number of strictly typed values.
You can then 'use' the injected values from any method called from within the context of the Scope.
In the above example we inject two values:
an int with a key 'ageKey' and a value 18.
a String with a key 'nameKey' and a value of 'brett'.
The age and name values are retrieved using the use
method and the ScopeKey they where injected with.
You will notice that we pass the string 'main' to the Scope. This is an optional argument debugName
. We recommend that you always pass a debugName
as it is included when an Scope related exception is thrown and makes it easier to identify the source of a problem.
ScopeKey
To inject and use a value you must create a typed key for each value using a ScopeKey:
As the ScopeKey is typed the values returned from the use
call are also correctly typed.
ScopeKeys are declared globally and it's is standard practice to place you Keys in a separate dart library as they need to be available at both the injection site and the use
site.
You will notice that with the first two examples we provide the optional string argument debugName
. We recommend that you always pass a debugName
as it is included when an ScopeKey related exception is thrown and makes it easier to identify the source of a problem.
Example
We start by defining ScopeKeys for each value we want to inject.
When then create a client (the Greeter class) that will 'use' values injected into the Scope.
Values are made available by creating aScope and injecting each of key/value pair into the Scope
.
Once we have injected values into the Scope we call the Scope's run
method.
Any method called directly or indirectly from within the run
method has access to each of the values injected into the Scope.
You can create a Scope anywhere in your code that it might be useful.
Last updated