dimsuz
dimsuz

Reputation: 9207

Is there a way to re-add a Module to a Scope in a Toothpick DI library?

I have a use case which seems to indicate the need to have something like scope.removeModules(...) available in the Toothpick DI library.

In an Android application I have a module which creates a binding to the class which talks to a server through a Retrofit-library interface. The actual server url is specified at the time of that class creation and is therefore supplied as a Module's constructor parameter:

class NetworkModule(serverUrl: String) {
   init {
     bind(MyServerApi::class.java).toInstance(createMyApi(serverUrl));
   }
}

Now the issue is that this module is an app-wide one and must be added to an application scope (root scope), BUT serverUrl can be reconfigured later by user. Which means that MyServerApi would need to be recreated. And it seems like it would be great to have the ability to just remove + add again this whole module to the root scope once url is changed.

This way whole app will still be able to do Toothpick.openScope(getApplication()) and get access to the latest configured instance of the MyServerApi talking to the proper serverUrl.

I wonder if I am missing some design choice made by this library which would make the above possible without adding removeModules() method to the library?

Upvotes: 1

Views: 676

Answers (1)

Snicolas
Snicolas

Reputation: 38168

There is no way to remove a module in TP. Doing so would put the scope in a strange state, as some dependencies of the module's bindings would still be preserved while the initial bindings in the module would not be present anymore. Honestly, it's real hard even to give a clear semantic to what this would mean.

BUT, the good thing is that you can achieve a complete wipe out of your bindings with TP: just declare a special scope for them and close this scope. It will remove all things properly and cleanly, all things that were supposed to be instantiated or recycled in the same scope as your bindings will also be wiped out while insuring the integrity of the scopes above it.

Simply add an intermediary scope right below the application scope and make sure all scopes will use it as a parent when they are opened.

Upvotes: 0

Related Questions