Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 913
dimsuz Avatar asked Mar 21 '18 17:03

dimsuz


1 Answers

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));
like image 150
dipcore Avatar answered Oct 19 '22 23:10

dipcore