Skip to content

Commit 80cf7d2

Browse files
authored
Merge pull request #62 from pepakriz/scoped-container-fix
Scoped container creates new instance for first time only
2 parents 38d26cd + f16fe40 commit 80cf7d2

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/ContainerInstance.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,9 @@ export class ContainerInstance {
105105
if (service && this !== globalContainer) {
106106
const clonedService = Object.assign({}, service);
107107
clonedService.value = undefined;
108-
return this.getServiceValue(identifier, clonedService);
108+
const value = this.getServiceValue(identifier, clonedService);
109+
this.set(identifier, value);
110+
return value;
109111
}
110112

111113
return this.getServiceValue(identifier, service);
@@ -151,6 +153,11 @@ export class ContainerInstance {
151153
*/
152154
set(token: Token<any>, value: any): this;
153155

156+
/**
157+
* Sets a value for the given type or service name in the container.
158+
*/
159+
set(token: ServiceIdentifier, value: any): this;
160+
154161
/**
155162
* Sets a value for the given type or service name in the container.
156163
*/
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import "reflect-metadata";
2+
import {Container} from "../../../src/Container";
3+
import {Service} from "../../../src/decorators/Service";
4+
5+
describe("github issues > #61 Scoped container creates new instance of service every time", function() {
6+
7+
beforeEach(() => Container.reset());
8+
9+
it("should work properly", function() {
10+
11+
@Service()
12+
class Car {
13+
public serial = Math.random();
14+
}
15+
16+
const fooContainer = Container.of("foo");
17+
const barContainer = Container.of("bar");
18+
19+
const car1Serial = Container.get(Car).serial;
20+
const car2Serial = Container.get(Car).serial;
21+
22+
const fooCar1Serial = fooContainer.get(Car).serial;
23+
const fooCar2Serial = fooContainer.get(Car).serial;
24+
25+
const barCar1Serial = barContainer.get(Car).serial;
26+
const barCar2Serial = barContainer.get(Car).serial;
27+
28+
car1Serial.should.be.equal(car2Serial);
29+
fooCar1Serial.should.be.equal(fooCar2Serial);
30+
barCar1Serial.should.be.equal(barCar2Serial);
31+
32+
car1Serial.should.not.be.equal(fooCar1Serial);
33+
car1Serial.should.not.be.equal(barCar1Serial);
34+
fooCar1Serial.should.not.be.equal(barCar1Serial);
35+
});
36+
37+
});

0 commit comments

Comments
 (0)