nicojs / typed-inject

Type safe dependency injection for TypeScript
Apache License 2.0
443 stars 23 forks source link

Question : How to use typed-inject in sub package? #69

Open stevebeauge opened 1 month ago

stevebeauge commented 1 month ago

Hello,

I'm looking for a simple, type safe, IOC container and I found typed-inject. I'm only starting my journey, so I hope my question won't be obvious.

I'm maintaining a large mono repository which contains several applications and a bunch of private packages.

AFAIK, type safety come thanks to the createInjector typings which "stacks" the tokens and requirement for all injections (via the inject property).

It works well in a single package application, because all injections are known.

However, in a sub package, I don't have access to the actual app injector, because it's instantiated at the top level package.

A concrete example in our case, is that we have multiple apps that have not the same authentication behavior (some are vite web apps, some are browser extension and some are MS Office addins), but we still want to share common component.

We have a IHttpService interface, and multiple implementations that will take care of the specificities.

In a shared component library, how can we get the actual service implementation ?

Currently, we have one react context for each sort of service, but it's reaching a hard-to-maintain state compared to what an IOC container would provide.

How can typed-inject could help ?

stevebeauge commented 1 month ago

As a previous IOC container, I used https://www.vrdmn.com/2019/03/using-service-scopes-to-decouple.html, which I cannot use anymore (it only works in the Microsoft SharePoint framework)

Microsoft introduced in this container the concept of "ServiceKey", this is similar to what the token typed-inject supports, but the type is included in the ServiceKey. This way, I could query the service by the service key, and I will get the typed object directly (or fail if not present).

Maybe we could achive something similar with typedinject ?