Attribute Macro prebuilt
#[prebuilt]
Expand description
Define a prebuilt type.
Prebuilt types are constructed outside of Pavex’s dependency injection framework but can still be injected as dependencies into your components.
§Example
use pavex::prebuilt;
#[prebuilt]
#[derive(Debug)]
pub struct DatabaseConnectionPool {
// Connection pool initialized elsewhere
}
§Guide
Check out the “Dependency injection” section of Pavex’s guide for a thorough introduction to dependency injection in Pavex applications.
§Registration
You can register a prebuilt type with your application in two ways:
- Use
Blueprint::prebuilt
to register a single prebuilt type - Use
Blueprint::import
to import multiple prebuilt types in bulk
The #[prebuilt]
macro generates a constant that you can use to refer to a specific
prebuilt type when invoking Blueprint::prebuilt
.
§Arguments
The sections below provide an exhaustive list of all the arguments and flags supported by the prebuilt
macro:
Name | Kind | Required |
---|---|---|
id | Argument | No |
clone_if_necessary | Flag | No |
never_clone | Flag | No |
allow | Argument | No |
§id
When using Blueprint::prebuilt
, Pavex generates a constant named after your type
(converted to UPPER_SNAKE_CASE) that you use to refer to the prebuilt type.
The id
argument allows you to customize the name of the generated constant.
§Example
use pavex::{prebuilt, Blueprint};
#[prebuilt(id = "DB_POOL")]
// 👆 Custom identifier
#[derive(Debug)]
pub struct DatabaseConnectionPool {
// [...]
}
let mut bp = Blueprint::new();
// Use the custom identifier when registering
bp.prebuilt(DB_POOL);
§clone_if_necessary
By default, Pavex will not clone prebuilt types. The clone_if_necessary
flag
allows Pavex to invoke .clone()
on the type if it helps satisfy Rust’s borrow checker.
The prebuilt type must implement the Clone
trait.
This flag is mutually exclusive with never_clone
.
§Example
use pavex::prebuilt;
#[prebuilt(clone_if_necessary)]
// 👆 Allow cloning when needed
#[derive(Debug, Clone)]
pub struct DatabaseConnectionPool {
// [...]
}
§never_clone
The never_clone
flag explicitly prevents Pavex from cloning the prebuilt type.
This is the default behavior for prebuilt types, so this flag is typically used
for clarity and explicitness.
This flag is mutually exclusive with clone_if_necessary
.
§Example
use pavex::prebuilt;
#[prebuilt(never_clone)]
// 👆 Explicitly prevent cloning (default behavior)
#[derive(Debug)]
pub struct NonCloneableResource {
// Some resource that shouldn't be cloned
file_handle: std::fs::File,
}
Pavex will report an error during the code-generation phase if cloning is required but forbidden.
§allow
The allow
argument can be used to suppress specific warnings.
Currently, only one value is supported:
unused
: Suppress warnings if this prebuilt type is registered but never used
§Example
use pavex::prebuilt;
#[prebuilt(allow(unused))]
// 👆 Don't warn if unused
#[derive(Debug, Clone)]
pub struct DatabaseConnectionPool {
// [...]
}