Syrette
The convenient dependency injection & inversion of control framework for Rust.
Namesake
From the syrette Wikipedia article.
A syrette is a device for injecting liquid through a needle. It is similar to a syringe except that it has a closed flexible tube (like that typically used for toothpaste) instead of a rigid tube and piston.
Features
- A dependency injection and inversion of control container
- Autowiring dependencies
- API inspired from the one of InversifyJS
- Helpful error messages
- Enforces the use of interface traits
- Supports generic implementations & generic interface traits
- Binding singletons
- Injection of third-party structs & traits
- Named bindings
- Async factories
Optional features
factory
. Binding factories (Rust nightly required)prevent-circular
. Detection and prevention of circular dependencies. (Enabled by default)async
. Asynchronous support
To use these features, you must enable it in Cargo.
Why inversion of control & dependency injection?
The reason for practing IoC and DI is to write modular & loosely coupled applications.
This is what we're trying to avoid:
The following is better:
}
This will however grow quite tiresome sooner or later when you have a large codebase with many dependencies and dependencies of those and so on. Because you will have to specify the dependencies someplace
let foobar = new
This is where Syrette comes in.
Motivation
Other DI & IoC libraries for Rust are either unmaintained (di for example), overcomplicated and requires Rust nightly for all functionality (anthill-di for example) or has a weird API (teloc for example).
The goal of Syrette is to be a simple, useful, convenient and familiar DI & IoC library.
Example usage
use Error;
use injectable;
use *;
use TransientPtr;
For more examples see the examples folder.
Terminology
Transient A type or trait that is unique to owner.
Singleton A type that only has a single instance. The opposite of transient. Generally discouraged.
Interface A type or trait that represents a type (itself in the case of it being a type).
Factory A function that creates new instances of a specific type or trait.
Default factory A function that takes no arguments that creates new instances of a specific type or trait.
Rust version requirements
Syrette requires Rust >= 1.62.1 to work. This is mainly due to the dependency on Linkme.
Todo
- Add support for generic factories
Contributing
You can reach out by joining the mailing list.
This is the place to submit patches, feature requests and to report bugs.