[英]Is there a way to ignore binding override in Toothpick?
Say I have scope S1
which has the module with the binding:假设我有范围S1
,其中包含带有绑定的模块:
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
):然后S2
范围以S1
作为父级( S1 -> S2
)打开,并且S2
定义相同的绑定(因为它是独立的并且对S1
一无所知):
bind(Repository.class).to(RepositoryImpl.class).singletonInScope()
By default Toothpick overrides parent scope dependencies, so S2
will have a new RepositoryImpl
created.默认情况下,Toothpick 会覆盖父范围依赖项,因此S2
将创建一个新的RepositoryImpl
。
Question : Is there a way to reuse the one created in S1
and ignore an S2
binding?问题:有没有办法重用在S1
中创建的绑定并忽略S2
绑定?
This requirement comes from the fact that sometimes there are independent application components which reside in different scopes and which share that Repository
dependency.这个要求来自这样一个事实,即有时存在独立的应用程序组件,它们位于不同的范围内并且共享该Repository
依赖性。 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.所以我想强加的唯一规则是:一些组件(不知道究竟是哪个组件)创建Repository
,所有这些都是稍后在当前和子范围中创建的 - 重用它。
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如果 S1 是 S2 的父范围,您可以使用 getParentScope() 方法执行相同的操作
Scope s1Scope = s2Scope.getParentScope();
And then just load required singleton from S1 scope然后从 S1 范围加载所需的单例
Repository s1Repository = s1Scope.getInstance(Repository.class);
If you want to do it in the S2 module you can simply do如果你想在 S2 模块中做,你可以简单地做
bind(Repository.class).toProviderInstance(() -> Toothpick.openScope('s1-scope-name').getInstance(Repository.class));
When you develop an app built from multi independant components with Toothpick, you may go to this direction:当您使用 Toothpick 开发由多个独立组件构建的应用程序时,您可能会朝这个方向发展:
Every independant component, should own 2 toothpick modules.每个独立的组件,应该拥有 2 个牙签模块。
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.在第二个中,您将定义 in 和 out 依赖关系,这些依赖关系将连接到其他独立组件,最终构建一个集成的 componenet 系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.