Skip to main content

ServiceCollection

Struct ServiceCollection 

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

Represents a service collection.

Implementations§

Source§

impl ServiceCollection

Source

pub fn new() -> Self

Creates and returns a new instance of the service collection.

Source

pub fn is_empty(&self) -> bool

Returns true if the collection contains no elements.

Source

pub fn len(&self) -> usize

Returns the number of elements in the collection.

Source

pub fn clear(&mut self)

Removes all elements from the collection.

Source

pub fn remove(&mut self, index: usize) -> ServiceDescriptor

Removes and returns the element at position index within the collection.

§Argument
  • index - The index of the element to remove
§Panics

Panics if index is out of bounds.

Source

pub fn add<T: Into<ServiceDescriptor>>(&mut self, descriptor: T) -> &mut Self

Adds a service using the specified service descriptor.

§Arguments
Source

pub fn try_add<T: Into<ServiceDescriptor>>( &mut self, descriptor: T, ) -> &mut Self

Adds a service using the specified service descriptor if the service has not already been registered.

§Arguments
Source

pub fn try_add_to_all<T: Into<ServiceDescriptor>>( &mut self, descriptor: T, ) -> &mut Self

Adds a service using the specified service descriptor if the service with same service and implementation type has not already been registered.

§Arguments
Source

pub fn try_add_all( &mut self, descriptors: impl IntoIterator<Item = ServiceDescriptor>, ) -> &mut Self

Adds the specified service descriptors if each of the services are not already registered with the same service and implementation type.

§Arguments
Source

pub fn replace<T: Into<ServiceDescriptor>>( &mut self, descriptor: T, ) -> &mut Self

Removes the first service descriptor with the same service type and adds the replacement.

§Arguments
Source

pub fn try_replace<T: Into<ServiceDescriptor>>( &mut self, descriptor: T, ) -> &mut Self

Adds or replaces a service with the specified descriptor if the service has not already been registered.

§Arguments
Source

pub fn remove_all<T: Any + ?Sized>(&mut self) -> &mut Self

Removes all specified descriptors of the specified type.

Source

pub fn build_provider(&self) -> Result<ServiceProvider, ValidationError>

Builds and returns a new ServiceProvider.

Source

pub fn iter( &self, ) -> impl ExactSizeIterator<Item = &ServiceDescriptor> + DoubleEndedIterator

Gets a read-only iterator for the collection

Source

pub fn decorate<TSvc: ?Sized + Any, TImpl>( &mut self, activate: impl Fn(&ServiceProvider, Ref<TSvc>) -> Ref<TSvc> + 'static, ) -> &mut Self

Decorates an existing service descriptor with a new one that wraps the original.

§Arguments
  • activate - The function that will be called to decorate the resolved service instance
§Remarks

This function will only decorate the last registered ServiceDescriptor for the specified service type. If there are multiple, the others are ignored. If you need to decorate all services of a particular service type, consider using decorate_all instead. If the service to be decorated is not registered, this function does nothing. The decorator ServiceDescriptor is created with the same lifetime as the original service registration. The implementation type of the decorator is determined by the generic parameter TImpl. If the original and decorator implementation types are the same, the original, decorated ServiceDescriptor is not replaced to prevent infinite recursion.

§Example
use di::{injectable, Injectable, ServiceCollection, Ref};

trait Counter {
    fn count(&self) -> usize;
}

#[injectable(Counter)]
struct SingleCount;

impl Counter for SingleCount {
    fn count(&self) -> usize {
        1
    }
}

struct DoubleCount(Ref<dyn Counter>);

impl Counter for DoubleCount {
    fn count(&self) -> usize {
        self.0.count() * 2
    }
}

let provider = ServiceCollection::new()
    .add(SingleCount::transient())
    .decorate::<dyn Counter, DoubleCount>(|_, decorated| Ref::new(DoubleCount(decorated)))
    .build_provider()
    .unwrap();
let counter = provider.get_required::<dyn Counter>();

assert_eq!(counter.count(), 2);
Source

pub fn decorate_all<TSvc: ?Sized + Any, TImpl>( &mut self, activate: impl Fn(&ServiceProvider, Ref<TSvc>) -> Ref<TSvc> + 'static, ) -> &mut Self

Decorates all existing service descriptors with a new one that wraps the original.

§Arguments
  • activate - The function that will be called to decorate the resolved service instance
§Remarks

This function decorates all registered ServiceDescriptor instances for the specified service type. If there are none, this function does nothing. The decorator ServiceDescriptor is created with the same lifetime as the original. If the original, decorated ServiceDescriptor is the same the decorator type, it is ignored.

§Example
use di::{injectable, Injectable, ServiceCollection, Ref};
use std::sync::atomic::{AtomicUsize, Ordering};

trait Feature {
    fn show(&self);
}

#[injectable(Feature)]
struct Feature1;

impl Feature for Feature1 {
    fn show(&self) {
    }
}

#[injectable(Feature)]
struct Feature2;

impl Feature for Feature2 {
    fn show(&self) {
    }
}

#[injectable]
struct Tracker(AtomicUsize);

impl Tracker {
    fn track(&self) {
        self.0.fetch_add(1, Ordering::Relaxed);
    }

    fn count(&self) -> usize {
        self.0.load(Ordering::Relaxed)
    }
}

struct FeatureTracker {
    feature: Ref<dyn Feature>,
    tracker: Ref<Tracker>,
};

impl Feature for FeatureTracker {
    fn show(&self) {
        self.tracker.track();
        self.feature.show();
    }
}

let provider = ServiceCollection::new()
    .add(Tracker::singleton())
    .try_add_to_all(Feature1::transient())
    .try_add_to_all(Feature2::transient())
    .decorate_all::<dyn Feature, FeatureTracker>(|sp, decorated| {
        Ref::new(FeatureTracker { feature: decorated, tracker: sp.get_required::<Tracker>() })
    })
    .build_provider()
    .unwrap();
let features = provider.get_all::<dyn Feature>();
let tracker = provider.get_required::<Tracker>();

for feature in features {
    feature.show();
}

assert_eq!(tracker.count(), 2);

Trait Implementations§

Source§

impl Debug for ServiceCollection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult

Formats the value using the given formatter. Read more
Source§

impl Default for ServiceCollection

Source§

fn default() -> ServiceCollection

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

impl Display for ServiceCollection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult

Formats the value using the given formatter. Read more
Source§

impl Index<usize> for ServiceCollection

Source§

type Output = ServiceDescriptor

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a> IntoIterator for &'a ServiceCollection

Source§

type Item = &'a ServiceDescriptor

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, ServiceDescriptor>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut ServiceCollection

Source§

type Item = &'a mut ServiceDescriptor

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, ServiceDescriptor>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for ServiceCollection

Source§

type Item = ServiceDescriptor

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<<ServiceCollection as IntoIterator>::Item>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.