inversify / InversifyJS

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
http://inversify.io/
MIT License
11.34k stars 719 forks source link

Feature Request: unbindOne/rebindOne #1477

Open dreamerblue opened 2 years ago

dreamerblue commented 2 years ago

Background

When using Inversify with possible multi-injection case, our framework have some requirements to control bound dependencies:

container.bind('Id').to(ClassA);
container.bind('Id').to(ClassB);
container.bind('Id').to(ClassC).inSingletonScope();

// In some cases like dynamic replacement or HMR clear, we need to unbind/rebind one dependency
// For example, to unbind `ClassB` only:

// cuz `container.get` can only return the instance, so we need to do use more complex way to maintain the constructor map in a wrapped method
const allBound = container.getAll('Id__ctor');
const index = allBound.indexOf(ClassB);
if (index > -1) allBound.splice(index, 1);
container.unbind('Id');
allBound.forEach(item => container.bind('Id').to(item));

Even we can self maintain the constructor map, it's not enough. We still need other metadata like scope, it will be a complex work.

Proposal

We are requesting a series methods to unbind/rebind a specified dependency like this:

container.unbindOne('Id', ClassB);
container.rebindOne('Id', ClassB).to(NewClassB);
Jameskmonger commented 11 months ago

Hi @dreamerblue, apologies for the late response here, the project went through a period of low maintenance.

Do you think the solution proposed by @logikaljay for an unbindTagged method will suit your needs here? We are aiming to publish this functionality in the 6.1.0 release.

cc @PodaruDragos

cc reacting users: @DerKatsche @jhechtf