DEV Community

Tu Bui
Tu Bui

Posted on

Reflect MetaData

_When your project is getting bigger and bigger.
Some solution to fix it is _Composition/Dependency Injection, Run-time Type Assertions, Testing, Decoration,... So a consistent approach is needed for various tools and libraries to be able to reason over metadata.

In my case, I'm trying to use Inversify package. It's require to use ReflectMetaData Package.

_Inversify is an Inversion of Control(IoC) container for TypeScript & TypeScript. It helps manage dependencies in applications. It uses decorators to mark classes and their dependencies, promoting modular, testable, and maintainable code.

_Reflect-Metadata
The reflect-metadata package adds a reflection API to JavaScript, which is used to add and retrieve metadata to/from JavaScript objects at runtime. In TypeScript, this allows the storage of type information and other metadata.

Connection
Decorators and Metadata:

Inversify relies on decorators to mark classes (@injectable) and their dependencies (@inject).
TypeScript decorators, in combination with reflect-metadata, enable the retrieval of type information at runtime. This is essential for Inversify to automatically inject the correct dependencies based on type information.
Automatic Dependency Resolution:

When you mark a class with @injectable, Inversify uses reflect-metadata to store metadata about the class and its constructor parameters.
When you use the @inject decorator, Inversify retrieves the type metadata for the constructor parameters, which allows the container to resolve and inject the appropriate instances automatically.

Top comments (0)