Crate springtime_di

source ·
Expand description

A dependency injection crate inspired by the Spring Framework in Java.

The philosophy of Springtime is to provide the means of easy dependency injection without unnecessary manual configuration, e.g. without the need to explicitly create dependencies and storing them in containers. As much work as possible is placed on compile-time metadata creation and automatic component discovery, thus allowing users to focus on the usage of components, rather than their creation and management. With an accent placed on attributes, dependency configuration becomes declarative (what I want to accomplish) leaving the gritty details the framework itself (how to accomplish what was requested).

Simple usage example

use springtime_di::component::Component;
use springtime_di::instance_provider::ComponentInstancePtr;
use springtime_di::{Component, component_alias, injectable};

// this is a trait we would like to use in our component
#[injectable]
trait TestTrait {}

// this is a dependency which implements the above trait and also is an injectable component
#[derive(Component)]
struct TestDependency;

// we're telling the framework it should provide TestDependency when asked for dyn TestTrait
#[component_alias]
impl TestTrait for TestDependency {}

// this is another component, but with a dependency
#[derive(Component)]
struct TestComponent {
    // the framework will know how to inject dyn TestTrait, when asked for TestComponent
    // more details are available in other parts of the documentation
    dependency: ComponentInstancePtr<dyn TestTrait + Send + Sync>,
}

Note: Send + Sync are only required when the threadsafe feature is enabled.

Features

  • derive - automatically import helper proc macros
  • threadsafe - use threadsafe pointers and Send + Sync trait bounds
  • async - turn all creation functions async

Modules

  • One of the basic blocks of dependency injection is a Component. Components are injectable objects, which themselves can contain dependencies to other components.
  • Functionality related to registering definitions of components. ComponentInstanceProviders should create Component instances based on those definitions, which can be registered automatically or manually.
  • Core functionality for creating Component instances.
  • The core functionality of creating and managing Component instances.
  • Component instances are contained in Scopes - containers which decide when to reuse or create an instance. There’s a global one for singletons, but there also can be other, specialized ones. Some can be simple, like PrototypeScope, while other can be quite complex and depend on external factors, e.g. tying the lifetime of instances to web sessions.

Attribute Macros

Derive Macros