Skip to content

Commit 7e6acc7

Browse files
author
mcibique
committed
Added option for overriding existing services with constant values in DI
1 parent 00ee4c4 commit 7e6acc7

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/di.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ let { lazyInject } = getDecorators(container);
77
let register = helpers.register(container);
88
let registerConstantValue = helpers.registerConstantValue(container);
99

10-
let override = function (identifier, dependencies, constraint) {
10+
function override (identifier, dependencies, constraint) {
1111
return function (constructor) {
1212
helpers.annotate(constructor, dependencies);
1313
if (container.isBound(identifier)) {
@@ -20,6 +20,14 @@ let override = function (identifier, dependencies, constraint) {
2020
};
2121
};
2222

23+
function overrideWithConstantValue (identifier, newConstantValue) {
24+
if (container.isBound(identifier)) {
25+
container.unbind(identifier);
26+
}
27+
28+
return registerConstantValue(identifier, newConstantValue);
29+
}
30+
2331
export {
2432
lazyInject,
2533
lazyInject as LazyInject,
@@ -28,7 +36,8 @@ export {
2836
registerConstantValue,
2937
registerConstantValue as RegisterConstantValue,
3038
override,
31-
override as Override
39+
override as Override,
40+
overrideWithConstantValue
3241
};
3342

3443
export default container;

test/unit/utils/di.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import sinon from 'sinon';
2+
import container, { overrideWithConstantValue } from '@di';
3+
4+
export function mockService (identifier) {
5+
let service = container.get(identifier);
6+
let serviceMock = sinon.mock(service);
7+
overrideWithConstantValue(identifier, service);
8+
return serviceMock;
9+
}

0 commit comments

Comments
 (0)