From 06da60f4b7df50cc389565aedaf2b5bb55737527 Mon Sep 17 00:00:00 2001 From: vsavkin Date: Thu, 6 Aug 2015 10:33:46 -0700 Subject: [PATCH] feat(di): added resolveAndInstantiate and instantiateResolved to Injector These two methods can be used to create objects in the context of the injector without storing them in the injector. --- modules/angular2/src/di/binding.ts | 2 -- modules/angular2/src/di/injector.ts | 23 +++++++++++++++++++++++ modules/angular2/test/di/injector_spec.ts | 23 +++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/modules/angular2/src/di/binding.ts b/modules/angular2/src/di/binding.ts index 1156a33e7a..a842894ea0 100644 --- a/modules/angular2/src/di/binding.ts +++ b/modules/angular2/src/di/binding.ts @@ -400,9 +400,7 @@ function _extractToken(typeOrFunc, metadata /*List | any*/, params: List
  • this._strategy.getMaxNumberOfObjects()) { throw new CyclicDependencyError(this, binding.key); } + return this._instantiate(binding, visibility); + } + private _instantiate(binding: ResolvedBinding, visibility: number): any { var factory = binding.factory; var deps = binding.dependencies; var length = deps.length; diff --git a/modules/angular2/test/di/injector_spec.ts b/modules/angular2/test/di/injector_spec.ts index e53d0d806c..35f3cde78f 100644 --- a/modules/angular2/test/di/injector_spec.ts +++ b/modules/angular2/test/di/injector_spec.ts @@ -395,6 +395,29 @@ export function main() { }); }); + describe('resolveAndInstantiate', () => { + it('should instantiate an object in the context of the injector', () => { + var inj = Injector.resolveAndCreate([Engine]); + var car = inj.resolveAndInstantiate(Car); + expect(car).toBeAnInstanceOf(Car); + expect(car.engine).toBe(inj.get(Engine)); + }); + + it('should not store the instantiated object in the injector', () => { + var inj = Injector.resolveAndCreate([Engine]); + inj.resolveAndInstantiate(Car); + expect(() => inj.get(Car)).toThrowError(); + }); + }); + + describe('instantiate', () => { + it('should instantiate an object in the context of the injector', () => { + var inj = Injector.resolveAndCreate([Engine]); + var car = inj.instantiateResolved(Injector.resolve([Car])[0]); + expect(car).toBeAnInstanceOf(Car); + expect(car.engine).toBe(inj.get(Engine)); + }); + }); describe("depedency resolution", () => { describe("@Self()", () => {