Attribute Macro constructor
#[constructor]
Expand description
Mark a function (or method) as a constructor.
Pavex will use the annotated function whenever it needs to create a new instance of its output type.
§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::constructor;
pub struct MyType {
// [...]
}
impl MyType {
#[constructor(request_scoped)]
pub fn new() -> Self {
Self {
// [...]
}
}
}
MyType::new
will be called whenever a new instance of MyType
is needed.
§Shortcuts
#[constructor]
requires you to specify the lifetime of the instance it creates (i.e. request_scoped
in the example above).
If you prefer a more concise syntax, you can use the lifetime-specific shortcuts:
use pavex::request_scoped;
pub struct MyType {
// [...]
}
impl MyType {
// Equivalent to #[constructor(request_scoped)]
#[request_scoped]
pub fn new() -> Self {
Self {
// [...]
}
}
}
#[request_scoped]
is equivalent to #[constructor(request_scoped)]
.
#[singleton]
is equivalent to #[constructor(singleton)]
.
#[transient]
is equivalent to #[constructor(transient)]
.