Skip to main content

Container

Struct Container 

Source
pub struct Container { /* private fields */ }
Expand description

The Dependency Injection (DI) Container.

This is the core registry for all providers, services, and configuration in a NestForge application. It mimics the behavior of the NestJS container but is adapted for Rust’s ownership and thread-safety models.

§Core Features

  • Singleton Registry: By default, registered services are singletons (Arc).
  • Thread Safety: Uses RwLock to allow concurrent reads (resolving) and exclusive writes (registering).
  • Type-Based Resolution: Services are stored and retrieved by their TypeId.
  • Scoped & Transient: Supports request-scoped and transient factories for more complex lifecycles.

Implementations§

Source§

impl Container

Source

pub fn new() -> Self

Creates a new, empty container.

This is equivalent to Container::default().

Source

pub fn scoped(&self) -> Self

Creates a “scoped” child container.

A scoped container shares the underlying singleton registry (inner) with its parent but has its own empty overrides map.

This is used during HTTP requests to create a context where request-scoped providers can be cached for the duration of that single request without affecting the global state.

Source

pub fn register<T>(&self, value: T) -> Result<(), ContainerError>
where T: Send + Sync + 'static,

Registers a value (singleton) into the container.

The value must be thread-safe (Send + Sync) and 'static.

§Example
container.register(AppConfig::default())?;
Source

pub fn replace<T>(&self, value: T) -> Result<(), ContainerError>
where T: Send + Sync + 'static,

Replaces an existing registration with a new value.

Unlike register, this will not error if the type is already present. It effectively updates the singleton instance.

Source

pub fn override_value<T>(&self, value: T) -> Result<(), ContainerError>
where T: Send + Sync + 'static,

Overrides a value in the current scope.

If called on a global container, it works like replace but stores the value in the overrides map, which takes precedence over inner.

If called on a scoped() container, the override only exists for that scope.

Source

pub fn is_type_registered_name( &self, type_name: &'static str, ) -> Result<bool, ContainerError>

Checks if a type with the given name is registered.

This relies on std::any::type_name matching what was stored.

Source

pub fn register_request_factory<T, F>( &self, factory: F, ) -> Result<(), ContainerError>
where T: Send + Sync + 'static, F: Fn(&Container) -> Result<T> + Send + Sync + 'static,

Registers a factory for request-scoped providers.

A request-scoped provider is created once per scoped() container (i.e., once per request) and then cached within that scope.

Source

pub fn register_transient_factory<T, F>( &self, factory: F, ) -> Result<(), ContainerError>
where T: Send + Sync + 'static, F: Fn(&Container) -> Result<T> + Send + Sync + 'static,

Registers a factory for transient providers.

A transient provider is created anew every single time it is resolved. It is never cached.

Source

pub fn resolve<T>(&self) -> Result<Arc<T>, ContainerError>
where T: Send + Sync + 'static,

Resolves (retrieves) a registered provider.

The search order is:

  1. Overrides (scoped instances)
  2. Singletons (global instances)
  3. Request-scoped factories (create and cache in overrides if found)
  4. Transient factories (create new instance)

Returns an Arc<T> so the service can be cheaply shared.

Source

pub fn resolve_in_module<T>( &self, module_name: &'static str, ) -> Result<Arc<T>, ContainerError>
where T: Send + Sync + 'static,

Trait Implementations§

Source§

impl Clone for Container

Source§

fn clone(&self) -> Container

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for Container

Source§

fn default() -> Container

Returns the “default value” for a type. Read more
Source§

impl<T> FromRequestParts<Container> for Inject<T>
where T: Send + Sync + 'static,

Source§

type Rejection = HttpException

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( parts: &mut Parts, state: &Container, ) -> Result<Self, Self::Rejection>

Perform the extraction.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoInjectableResult<T> for T

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,