pub struct ServiceContext<'a> { /* private fields */ }
Expand description
An interface to the service provided to the tasks during initialization. This the main point of interaction between with the service.
The context provides access to the runtime, resources, and allows adding new tasks.
Implementations§
Source§impl<'a> ServiceContext<'a>
impl<'a> ServiceContext<'a>
Sourcepub fn runtime_handle(&self) -> &Handle
pub fn runtime_handle(&self) -> &Handle
Provides access to the runtime used by the service.
Can be used to spawn additional tasks within the same runtime. If some task stores the handle to spawn additional tasks, it is expected to do all the required cleanup.
In most cases, however, it is recommended to use add_task
or its alternative
instead.
§Note
While tokio::spawn
and tokio::spawn_blocking
will work as well, using the runtime handle
from the context is still a recommended way to get access to runtime, as it tracks the access
to the runtimes by layers.
Sourcepub fn add_task<T: Task>(&mut self, task: T) -> &mut Self
pub fn add_task<T: Task>(&mut self, task: T) -> &mut Self
Adds a task to the service.
Added tasks will be launched after the wiring process will be finished and all the preconditions are met.
Sourcepub fn add_shutdown_hook(&mut self, hook: ShutdownHook) -> &mut Self
pub fn add_shutdown_hook(&mut self, hook: ShutdownHook) -> &mut Self
Adds a future to be invoked after node shutdown. May be used to perform cleanup tasks.
The future is guaranteed to only be polled after all the node tasks are stopped or timed out. All the futures will be awaited sequentially.
Sourcepub fn get_resource<T: Resource + Clone>(&mut self) -> Result<T, WiringError>
pub fn get_resource<T: Resource + Clone>(&mut self) -> Result<T, WiringError>
Attempts to retrieve the resource of the specified type.
§Panics
Panics if the resource with the specified ResourceId
exists, but is not of the requested type.
Sourcepub fn get_resource_or_insert_with<T: Resource + Clone, F: FnOnce() -> T>(
&mut self,
f: F,
) -> T
pub fn get_resource_or_insert_with<T: Resource + Clone, F: FnOnce() -> T>( &mut self, f: F, ) -> T
Attempts to retrieve the resource of the specified type. If the resource is not available, it is created using the provided closure.
Sourcepub fn get_resource_or_default<T: Resource + Clone + Default>(&mut self) -> T
pub fn get_resource_or_default<T: Resource + Clone + Default>(&mut self) -> T
Attempts to retrieve the resource of the specified type.
If the resource is not available, it is created using T::default()
.
Sourcepub fn insert_resource<T: Resource>(
&mut self,
resource: T,
) -> Result<(), WiringError>
pub fn insert_resource<T: Resource>( &mut self, resource: T, ) -> Result<(), WiringError>
Adds a resource to the service.
If the resource with the same type is already provided, the method will return an error.