DI in angular 2

248 Views Asked by At

I m actually studying the angular DI container and I need some informations.

In fact, reading the API, it seems that the Injector class accepts a Binding list in the factory arguments, and resolve it to acquire a ResolvedBinding list.

NB : https://angular.io/docs/js/latest/api/di/

I was wondering how the system is able to manage the conversion between Binding and ResolvedBing because :

  • Binding can return a value
  • Binding can return an alias
  • Binding can return a class
  • Binding can return a factory

The ResolvedBinding constructor is the following :

constructor(key:Key, factory:Function,...)

It seems that it's okay to return a factory when the needed is there (and class, if we admit that class are created through factories everytime), but what if I need to return only a value ? Does the fw creates a factory to specifically return the value ?

1

There are 1 best solutions below

0
On BEST ANSWER

A binding that is passed to the injector creation doesn't really return one of those values. A binding literally represents the binding configuration itself.

And as you might know, a binding get's a token and uses a factory function to tell the injector how to create and instance of a specific type. So the factory function that you're mentioning here, can be .toClass(), .toFactory(), .toValue().

The recipe is normalised before creating a ResolvedBinding out of it. Here's are the LOC that should clear things up: https://github.com/angular/angular/blob/master/modules/angular2/src/di/binding.ts#L221-L246