Providers behind a trait
Bind a provider as `Impl as dyn Trait`, so another feature injects the port without naming the concrete struct.
When another feature must call into posts/ without naming the concrete
struct, expose a pub trait and keep the impl module-private:
use std::sync::Arc;
use nest_rs::core::{async_trait, injectable};
#[async_trait]pub trait PostsService: Send + Sync { async fn list(&self) -> Result<Vec<Post>, Error>;}
#[injectable]pub(crate) struct PostsServiceImpl { #[inject] config: Arc<PostsConfig>,}
#[async_trait]impl PostsService for PostsServiceImpl { /* ... */ }#[module(providers = [PostsServiceImpl as dyn PostsService])]pub struct PostsModule;#[async_trait] is required on both the trait and the impl — an async method
in a dyn-compatible trait needs the boxed-future desugaring. It comes from
nest_rs::core, so this is not a manifest line.
Consumers inject Arc<dyn PostsService>, never PostsServiceImpl. There
is no exports = [...] list — Rust visibility plus the
as dyn Trait binding is the encapsulation primitive.
One instance under every key
Section titled “One instance under every key”The binding builds one PostsServiceImpl and holds it under its own type
and under each trait it is listed with, so [Impl as dyn A, Impl as dyn B] is
one instance. Its #[hooks], #[scheduled] and #[listeners] methods run on
the instance every Arc<dyn PostsService> consumer holds. Listing
PostsServiceImpl bare beside its binding is a compile error: the binding
already holds it.
Only a singleton
Section titled “Only a singleton”Only a singleton can be bound. Every consumer of Arc<dyn Trait> shares the
instance built at boot, so binding anything else is a compile error: an edge
host (#[controller], #[gateway], #[resolver], #[mcp]) is built at
mount, a scope = request provider once per request, and a
scope = transient provider on every resolution. Bind a plain #[injectable]
singleton, and reach a scoped provider through a Scoped<T> parameter
(provider scopes).
When you do not need to hide the impl, register PostsService directly
in PostsModule, as Providers does. The trait pattern is optional:
use it when a second feature needs the port without coupling to your
concrete type.