dimsuz
dimsuz

Reputation: 9207

Is there a way to ignore binding override in Toothpick?

Say I have scope S1 which has the module with the binding:

bind(Repository.class).to(RepositoryImpl.class).singletonInScope()

Then S2 scope gets opened with S1 as a parent (S1 -> S2) and S2 defines the same binding (because it's independent and knows nothing of S1):

bind(Repository.class).to(RepositoryImpl.class).singletonInScope()

By default Toothpick overrides parent scope dependencies, so S2 will have a new RepositoryImpl created.

Question: Is there a way to reuse the one created in S1 and ignore an S2 binding?

This requirement comes from the fact that sometimes there are independent application components which reside in different scopes and which share that Repository dependency. They know nothing of each other. These components can also be created in different order, depending on the scenario and use case.

So the only rule which I want to impose is this: some component (it is unknown exactly which one) creates Repository, all which are created later in current and child scopes - reuse it.

Upvotes: 9

Views: 450

Answers (2)

Anthony
Anthony

Reputation: 4049

When you develop an app built from multi independant components with Toothpick, you may go to this direction :

Every independant component, should own 2 toothpick modules.

  • one module that deals with internals dependencies (provided by the module itself)
  • one module that deals with externals dependencies (provided at integration level)

In the second one, you will define the in and out dependencies, that will be connected to the others independant components, to build at the end an integrated system of componenet.

Upvotes: 0

dipcore
dipcore

Reputation: 190

To get early opened scope anywhere in your code you can just use

Scope s1Scope = Toothpick.openScope('s1-scope-name');

In case S1 is parent scope of S2 you can do the same by using getParentScope() method

Scope s1Scope = s2Scope.getParentScope();

And then just load required singleton from S1 scope

Repository s1Repository = s1Scope.getInstance(Repository.class);

If you want to do it in the S2 module you can simply do

bind(Repository.class).toProviderInstance(() -> Toothpick.openScope('s1-scope-name').getInstance(Repository.class));

Upvotes: 3

Related Questions