owja / ioc

:unicorn: lightweight (<1kb) inversion of control javascript library for dependency injection written in typescript
MIT License
287 stars 13 forks source link

Inject a service that requires constructor arguments ? #56

Closed vic1707 closed 2 years ago

vic1707 commented 2 years ago

Id like to be able to inject a class that requires arguments for it's constructor which would give more flexibility for some use cases.

Describe the solution you'd like I think a rework of the Factory type could do the trick, for now it doesn't accept any parameters 🤔 the idea, if possible, would be to usesomething like this container.bind(<symbol>).toFactory( (...args: InjectedConstructorArgs) => new Injected(...args)) ) and then resolveContainer(<symbol>)(...args)

Describe alternatives you've considered put the constructor logic in another function that is called manually after injection

hbroer commented 2 years ago

Hey,

with the new 2.x it will be possible after a type change to pass some custom arguments to plugins: https://github.com/owja/ioc/projects/2#card-82636307

With a small additional change it could be possible to pass the arguments to factories too.

I am not a big fan of this but I will add it if it helps to solve a problem. :-) I am not sure if I can make the arguments typesafe.

vic1707 commented 2 years ago

Fantastic ^^!

I am not a big fan of this

Why? Is it a bad practice? 🤔

if it helps to solve a problem

I don't really have a problem with not having the feature I just moved the constructor logic to another function that I call manually. The only "problem" is that a property was defined in the constructor resulting in me using a non-null-assertion in another function which I don't like.

As for typesafe arguments I think this can help https://stackoverflow.com/questions/43481518/get-argument-types-for-function-class-constructor

I'd love to try implementing this feature and will surely try if you haven't started yet.

hbroer commented 2 years ago

I am not a big fan of this

Why? Is it a bad practice? 🤔

it just adds complexity :-D

57 (just to link your PR here)