My frontend application in react-native utilizes inversify-js for service classes.
I have implemented an IOC structure where services are shared as singleton instances, each with an init/destroy method to manage internal state.
While the init/destroy mechanism works well, I am seeking a way to "clear" the inversify container singletons to rebuild all services from scratch when needed.
For example:
src/services/A.ts
@injectable()
export class A extends Service {
constructor() {
super();
}
init() {
super.init();
// [...] Initialize A's state
}
destroy() {
// [...] Destroy A's state
super.destroy();
}
method() {
// [...] Provide functionality to other services (maintaining A's state)
}
}
src/inversify/container.ts
export const containerModule = new ContainerModule((bind) => {
// Services
bind<A>(A).toSelf().inSingletonScope();
});
const container = new Container();
container.load(containerModule);
export default container;
index.ts
let a = container.get<A>(A);
// [...] use service
// Resetting the container and creating new singleton instances
container.unbind(A);
container.bind<A>(A).toSelf().inSingletonScope();
a = container.get<A>(A);
For more information on resetting scoped containers in InversifyJS, you can refer to this stackoverflow thread: Reset scoped container in inversifyjs