pavex

Attribute Macro singleton

#[singleton]
Expand description

Mark a function (or method) as a singleton constructor.

Singleton constructors are invoked once (when the application starts up) to create a new instance of their output type. The created instance is then shared across all requests for the lifetime of the application.

§Imports

The annotated function must be imported via Blueprint::import, otherwise it won’t be considered by Pavex.

§Guide

Check out the “Dependency injection” section of Pavex’s guide for a thorough introduction to dependency injection in Pavex applications.

§Example

use pavex::singleton;

pub struct MySharedResource {
    // [...]
}

impl MySharedResource {
    #[singleton]
    pub fn new() -> Self {
        Self {
            // [...]
        }
    }
}

MySharedResource::new will be called once at application startup, and the resulting instance will be shared across all requests.