di.js icon indicating copy to clipboard operation
di.js copied to clipboard

feat: inject non-annotated tokens as values

Open vojtajina opened this issue 11 years ago • 6 comments

If a token is an object or a non-annotated function/class and there is no other provider defined for this token, the default provider returns the value instead of calling it.

This is helpful for injecting third-party code (without instantiating it) that is not annotated. Eg. Node's native modules:

var fs = require('fs');

@Inject(fs.readFile)
class Foo {
  constuctor(readFile) {}
}

Fixes #30

BREAKING CHANGE: This means that every function/class (that should be called/instantiated) has to be annotated with @Inject, even if it takes no arguments.


See how templating and expressionist needs to be refactored: https://github.com/angular/templating/pull/35 https://github.com/angular/expressionist.js/pull/13

Review on Reviewable

vojtajina avatar May 09 '14 11:05 vojtajina

One problem with your example, though I'm not sure it's something to mitigate, but just something that peoples need to know. If fs.readFile depends on being called as a method and not a function this will go nuclear.

Alxandr avatar May 10 '14 03:05 Alxandr

@Alxandr that's a good point, you would have to inject fs to fix that...

vojtajina avatar May 10 '14 18:05 vojtajina

There is a discussion about this PR at https://groups.google.com/forum/#!topic/angular-dev/sN4cxlqHtKE

Without this feature, we might provide additional module that users would have to load to enable this. Something like https://gist.github.com/vojtajina/0a3a59f28ea9b3b5cef0

vojtajina avatar May 10 '14 18:05 vojtajina

@vojtajina or fs.readFile.bind(fs).

Alxandr avatar May 10 '14 18:05 Alxandr

I must say that I don't thin the injector.bind(fs.readFile).toValue(fs.readFile); is very intuative. If the @Provider syntax will be replaced by the bind syntax then it might make sense. (Part of the confusion is the existing javascript function.bind method).

larsno avatar Dec 01 '14 23:12 larsno

Is there any update on this pr?

dmtrs avatar May 19 '15 17:05 dmtrs