Expand description
Syrette
Syrette is a framework for utilizing inversion of control & dependency injection.
§Example
use std::error::Error;
use syrette::ptr::TransientPtr;
use syrette::{injectable, DIContainer};
trait IWeapon
{
fn deal_damage(&self, damage: i32);
}
struct Sword {}
#[injectable(IWeapon)] // Makes Sword injectable with a interface of IWeapon
impl Sword
{
fn new() -> Self
{
Self {}
}
}
impl IWeapon for Sword
{
fn deal_damage(&self, damage: i32)
{
println!("Sword dealt {} damage!", damage);
}
}
trait IWarrior
{
fn fight(&self);
}
struct Warrior
{
weapon: TransientPtr<dyn IWeapon>,
}
#[injectable(IWarrior)] // Makes Warrior injectable with a interface of IWarrior
impl Warrior
{
fn new(weapon: TransientPtr<dyn IWeapon>) -> Self
{
Self { weapon }
}
}
impl IWarrior for Warrior
{
fn fight(&self)
{
self.weapon.deal_damage(30);
}
}
fn main() -> Result<(), Box<dyn Error>>
{
let mut di_container = DIContainer::new();
// Creates a binding of the interface IWeapon to the concrete type Sword
di_container.bind::<dyn IWeapon>().to::<Sword>()?;
// Creates a binding of the interface IWarrior to the concrete type Warrior
di_container.bind::<dyn IWarrior>().to::<Warrior>()?;
// Create a transient IWarrior with all of its dependencies automatically injected
let warrior = di_container.get::<dyn IWarrior>()?.transient()?;
warrior.fight();
println!("Warrior has fighted");
Ok(())
}
Re-exports§
pub use di_container::asynchronous::AsyncDIContainer;
async
pub use di_container::blocking::DIContainer;
Modules§
- dependency_
history - Dependency history.
- di_
container - Dependency injection container types.
- errors
- Error types for various components of the library.
- future
async
- Future related utilities.
- interfaces
- Various useful interfaces.
- ptr
- Smart pointer type aliases.
Macros§
- declare_
default_ factory factory
- Shortcut for declaring a default factory.
- declare_
interface - Declares the interface trait of a implementation.
- di_
container_ bind - Shortcut for creating a DI container binding for a injectable without a declared interface.
Attribute Macros§
- factory
factory
- Makes a type alias usable as a factory interface.
- injectable
- Makes a type injectable.
- named
- Used to declare the name of a dependency in the constructor of a impl block decorated
with
injectable
.