DEV Community

Typescript Dependency Injection in 200 LOC

Darcy Rayner on January 23, 2019

One of the most common patterns in object oriented programming is dependency injection, and the inversion of control principle, (IOC). IOC containe...
Collapse
 
abraham profile image
Abraham Williams

I've found the reflect-metadata library a bit heavy to ship with apps so you might be interested in the @abraham/reflection alternative I wrote. I actually just released v0.5.0.

Collapse
 
darcyrayner profile image
Darcy Rayner

Nice, I might have to give that a try on my next Angular project.

Collapse
 
feralcode profile image
F Ξ R Λ L

I love typescript but never take advantage of the more advanced features in my codebases (nodejs, react) because of the rejection I get from most teams when trying to introduce it into our code base.

Great article, keep up the awesome work.

Collapse
 
darcyrayner profile image
Darcy Rayner

I think it's fair that teams should try to fight against too much complexity in their codebase, but sometimes a slightly more complex idea like Inversion of Control can dramatically simplify everything else. It's a tradeoff, and there is not always an easy answer about the best way to do things. Just keep making the case to try new ideas.

Collapse
 
mindplay profile image
Rasmus Schultz

See also this much more minimalist approach - 10 lines of code and no dependencies:

dev.to/mindplay/minimal-di-contain...

I only wish I could figure out how to type-hint it correctly. (I don't even know that it's possible - short of manually typing out the interfaces, but it really ought to be possible with inference...)