@Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var providers = ReflectiveInjector.resolve([Car, Engine]); var injector = ReflectiveInjector.fromResolvedProviders(providers); expect(injector.get(Car) instanceof Car).toBe(true);
class ParentProvider {} class ChildProvider {} var parentProviders = ReflectiveInjector.resolve([ParentProvider]); var childProviders = ReflectiveInjector.resolve([ChildProvider]); var parent = ReflectiveInjector.fromResolvedProviders(parentProviders); var child = parent.createChildFromResolved(childProviders); expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true); expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true); expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
@Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Engine]); var car = injector.resolveAndInstantiate(Car); expect(car.engine).toBe(injector.get(Engine)); expect(car).not.toBe(injector.resolveAndInstantiate(Car));
@Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Engine]); var carProvider = ReflectiveInjector.resolve([Car])[0]; var car = injector.instantiateResolved(carProvider); expect(car.engine).toBe(injector.get(Engine)); expect(car).not.toBe(injector.instantiateResolved(carProvider));
The following example creates an Injector configured to create Engine and Car.
@Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]); var car = injector.get(Car); expect(car instanceof Car).toBe(true); expect(car.engine instanceof Engine).toBe(true);
Notice, we don't use the new operator because we explicitly want to have the Injector resolve all of the object's dependencies automatically.