Skip to main content

PostConstruct

Trait PostConstruct 

Source
pub trait PostConstruct: Send + Sync {
    // Required method
    fn post_construct<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn Error + Sync + Send>>> + Send + 'async_trait>>
       where 'life0: 'async_trait,
             Self: 'async_trait;
}
Expand description

Trait for post-construction lifecycle hooks.

When a type has a method annotated with #[injectable(post_construct)], the derive macro generates an implementation of this trait that calls the annotated method.

§Execution Order

Post-construct hooks run after the constructor returns but before the value is returned from the provider. This ensures the instance is fully initialized before any consumer receives it.

§Error Handling

If a post_construct hook returns an error, the entire resolution fails with InjectableError::LifecycleHookFailed. The instance is discarded — it will not be available to consumers.

§Use Cases

  • Database connection establishment
  • Cache warming
  • Spawning background workers
  • Registering with external services

§Example

#[derive(Injectable)]
pub struct Database {
    pool_size: usize,
}

impl Database {
    #[injectable(ctor)]
    pub async fn new() -> Self { Self { pool_size: 10 } }

    #[injectable(post_construct)]
    async fn connect(&self) -> Result<(), std::io::Error> {
        self.establish_connection().await?;
        Ok(())
    }
}

Hooks that cannot fail may return ():

#[injectable(post_construct)]
fn log_startup(&self) {
    println!("Service started");
}

Required Methods§

Source

fn post_construct<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn Error + Sync + Send>>> + Send + 'async_trait>>
where 'life0: 'async_trait, Self: 'async_trait,

Run the post-construction hook.

Return Ok(()) on success, or an error to fail the resolution.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§