9

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.

Eby Jacob
  • 1,418
  • 1
  • 10
  • 28
dimsuz
  • 8,969
  • 8
  • 54
  • 88

2 Answers2

3

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));
dipcore
  • 190
  • 2
  • 8
  • So S2 has to know that Repository was created in S1. Is it possible to do this trick without such knowledge? Suppose I have S35 which wants to reuse Repository from S1, do I absolutely have to pass S1's name somehow to S35? – dimsuz May 21 '18 at 11:13
  • If I understand well what you mean, you want inject in S35 an instance that is available in S1, so S35 should know about S1, isn't it ? – Anthony Nov 05 '20 at 18:18
  • In addition, why do you define this binding, without it you, can you just get the repo from S1 ? – Anthony Nov 05 '20 at 18:20
0

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.

Anthony
  • 3,989
  • 2
  • 30
  • 52