[][src]Derive Macro async_injector_derive::Provider

#[derive(Provider)]
{
    // Attributes available to this derive:
    #[provider]
    #[dependency]
}

Helper derive to implement a provider.

Examples

/// Provider that describes how to construct a database.

#[derive(Serialize)]
pub enum Tag {
   DatabaseUrl,
   ConnectionLimit,
}

#[derive(Provider)]
struct DatabaseProvider {
    #[dependency(tag = "Tag::DatabaseUrl")]
    url: String,
    #[dependency(tag = "Tag::DatabaseUrl")]
    connection_limit: u32,
}

#[async_trait]
impl Provider for DatabaseProvider {
    type Output = Database;

    /// Constructor a new database and supply it to the injector.
    async fn build(self) -> Option<Self::Output> {
        match Database::connect(&self.url, self.connection_limit).await {
            Ok(database) => Some(database),
            Err(e) => {
                log::warn!("failed to connect to database: {}: {}", self.url, e);
                None
            }
        }
    }
}