Dependency Injection Container
// your classes// configure DI container;// in your entry point code;; // PRODUCTION; // object of AuthStorage; // History singleton will be returned
All definitions are resolved once and their result persists over the life of the container.
- Simple but powerful
- Does not requires decorators
Popular solutions like
reflect-metadata that allows to fetch argument types and based on
those types and do autowiring. Autowiring is a nice feature but the trade-off is decorators.
Disadvantages of other solutions
- I have to update my tsconfig because one package requires it.
- Let my components know about injections.
Why component Foo should know that it's injectable?
More details thoughts in my blog article
;;container.addDefinitions;; // PRODUCTION; // instance of AuthStorage; // instance of AuthStorage
When you specify raw values (i.e. don't use
rsdi will resolve it as it is.
object(ClassName) - the simplest scenario that will call
new ClassName(). When you need to pass arguments to the
constructor, you can use
construct method. You can refer to the already defined dependencies via the
If you need to call object method after initialization you can use
method it will be called after constructor.
You can use factory definition when you need more flexibility during initialisation.
container: IDIContainer will be
pass as an argument to the factory method. So you can resolve other dependencies inside the factory function.
Async factory definition
RSDI intentionally does not provide the ability to resolve asynchronous dependencies. The container works with resources. All resources will be needed sooner or later. The lazy initialization feature won't be of much benefit in this case. At the same time, mixing synchronous and asynchronous resolution will cause confusion primarily for the consumers themselves.
The following approach will work in most scenarios.
// UserRepository.ts// configureDI.ts;;;;container.addDefinitions;return container;}// main.ts;;