zazoomauro / node-dependency-injection

The NodeDependencyInjection component allows you to standarize and centralize the way objects are constructed in your application.
https://github.com/zazoomauro/node-dependency-injection/wiki
MIT License
280 stars 34 forks source link

Container overrides registered object? #161

Closed phuonghuynh closed 3 years ago

phuonghuynh commented 3 years ago

@zazoomauro Thanks for great library, I am using this for my project, it so simple and easy to use than other DI lib. I have an issue that need suggestion how to fix. I would like to set my container don't override registered object, sample code bellow.

const container = new ContainerBuilder();
const a = 123;

container.register('a').synthetic = true;
container.set('a', a);
console.log(container.get('a'));

const b = 234;
container.register('a').synthetic = true;
container.set('a', b);
console.log(container.get('a')); // expect print 123 ("a") , actually it prints "234" (b)
zazoomauro commented 3 years ago

Hello @phuonghuynh

may you have to check first if service was already registered like this:

const container = new ContainerBuilder();
const a = 123;

container.register('a').synthetic = true;
container.set('a', a);
console.log(container.get('a'));

const b = 234;
container.register('a').synthetic = true;
if (false === container.has('a')) {
  container.set('a', b);
}
console.log(container.get('a')); // expect print 123 ("a") , actually it prints "123" (a) 👍