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.
This commit is contained in:
vsavkin 2015-08-06 10:33:46 -07:00
parent ff1b110ae1
commit 06da60f4b7
3 changed files with 46 additions and 2 deletions

View File

@ -400,9 +400,7 @@ function _extractToken(typeOrFunc, metadata /*List<any> | any*/, params: List<Li
}
var lowerBoundVisibility = null;
;
var upperBoundVisibility = null;
;
for (var i = 0; i < metadata.length; ++i) {
var paramMetadata = metadata[i];

View File

@ -552,11 +552,34 @@ export class Injector {
return inj;
}
/**
* Resolves a binding and instantiates an object in the context of the injector.
*
* @param `binding`: either a type or a binding.
* @returns an object created using binding.
*/
resolveAndInstantiate(binding: Type | Binding) {
return this.instantiateResolved(Injector.resolve([binding])[0]);
}
/**
* Instantiates an object using a resolved bindin in the context of the injector.
*
* @param `binding`: a resolved binding
* @returns an object created using binding.
*/
instantiateResolved(binding: ResolvedBinding): any {
return this._instantiate(binding, PUBLIC_AND_PRIVATE);
}
_new(binding: ResolvedBinding, visibility: number): any {
if (this._constructionCounter++ > 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;

View File

@ -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()", () => {