Enhanced C#
Loyc library documentation
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events Pages
Nested classes | Public fields | Properties | Public Member Functions | List of all members
Loyc.Threading.AmbientService< T > Class Template Reference

Holds the shared state behind an ambient service (the Ambient Service Pattern): a global default instance, plus an async-local override installed by Set in a using statement. More...


Source file:
Inheritance diagram for Loyc.Threading.AmbientService< T >:
Loyc.Threading.AmbientService< T >.Saved

Remarks

Holds the shared state behind an ambient service (the Ambient Service Pattern): a global default instance, plus an async-local override installed by Set in a using statement.

This is based on AsyncLocal, which is reportedly slow. Value has a fast path for the case that no override is active anywhere.

Because the override is an AsyncLocal rather than a ThreadLocal, it flows across await points to continuations, even when they resume on a different thread.

Type Constraints
T :class 

Nested classes

struct  Saved
 Returned by Set; restores the previous ambient override (if any) when disposed. More...
 

Public fields

Value => _overrideCount == 0 ? _globalDefault : _override.Value ?? _globalDefault
 Gets the current T instance (the current async execution context's override if one is active, otherwise GlobalDefault. More...
 

Properties

GlobalDefault [get, set]
 The instance used by every execution context that has no ambient override from Set. It can be replaced app-wide. More...
 

Public Member Functions

 AmbientService (T globalDefault)
 
Saved Set (T newValue)
 Installs an ambient (async-local) override. Designed to be used in a using statement, which restores the old value at the end. More...
 

Member Function Documentation

Saved Loyc.Threading.AmbientService< T >.Set ( newValue)
inline

Installs an ambient (async-local) override. Designed to be used in a using statement, which restores the old value at the end.

An override installed inside an async method does not propagate up to its caller's context, so call Set in the same method as the using block that scopes it.

Member Data Documentation

T Loyc.Threading.AmbientService< T >.Value => _overrideCount == 0 ? _globalDefault : _override.Value ?? _globalDefault

Gets the current T instance (the current async execution context's override if one is active, otherwise GlobalDefault.

Property Documentation

T Loyc.Threading.AmbientService< T >.GlobalDefault
getset

The instance used by every execution context that has no ambient override from Set. It can be replaced app-wide.