Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 24, 2022 06:06 am GMT

Inversion of Control: Dependency Injection in Typescript

I've been working with Angular for a while now (over 2 years), and since I moved to another workplace, I've switched (mostly) to Stencil.

Stencil is a very nice compiler for Typescript that generates web components. If I were to place it, it would be a mixture between Angular and React. It uses decorators like Angular does (for the compiler to collect metadata and generate the output code based on that), and jsx/tsx with lifecycles just like React. It is a very powerfool tool to generate design systems.

In this design system that I've been working on, there was the problem of how to store the global state. I wanted to have a simple version of DI (since I really liked it in Angular). The big advantage of using a DI system is that you can easily mock the services in tests, instead of needing to overwrite the actual imports in jest (overwriting is fine, but on complicated setups where you want different configurations between iterations, it would get messy because if there is any reference to the module before it is mocked, the mock will not work).

So I came up with a simple solution for a global injectable service that did not care about the actual implementation.

First step would be to think about what the service that you want to write will do. Based on that, you can declare an interface with all the public methods of the service. Let's consider a simple service that sets and gets user information.

Then we would need to declare a UserServiceInstanceResolver static class that will receive an instance of a class implementation of this interface, and store it in order to be able to access it.

Last but not least, we can implement the actual service

And finally, whenever you want to actually instantiate the singleton service, you can just do it as such:

And the actual benefit, whenever you want to test any other component that uses this instance, you can easily instantiate a mock of the app on UserServiceInstanceResolver.Instantiate method.

This was all that I actually needed (just a root level global instance). But this code can be extended to support as well a per component instance (or hierarchy instance) and get a closer experience to Angular's DI.

Thank you for reading my article. If you enjoyed it, please hit that heart button so others can see it.


Original Link: https://dev.to/this-is-angular/inversion-of-control-dependency-injection-in-typescript-1dj9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To