如何避免在Scala中进行依赖注入? [英] How to avoid dependency injection in Scala?

查看:51
本文介绍了如何避免在Scala中进行依赖注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了没有体操PDF 的依赖注入表明不需要任何高级的DI框架,但这是我无法掌握的(至少没有具体示例)。我将尝试观看没有体操的依赖注射简单死亡依赖注入

在Java中使用Guice,如果A同时依赖于B和C,而B和C同时依赖于D,则将具有以下内容:

 公共类A {
@注入
公共A(B b,C c){
this.b = b;
this.c = c;
}
}

公共类B {
@注入
公共B(D d){
this.d = d;
}
}

公共类C {
@注入
公共C(D d){
this.d = d;
}
}

公共类D {/ * ... * /}

和一个模块,该模块说明要使用D的哪个实现,然后只需向注入器请求A的实例:

  A a =注射器.createInstance(A.class); 

鉴于上面URL中显示的内容,上面代码的Scala等效形式如何?



FWIW,我也在调查 https://github.com/dickwall/subcut/blob/master/GettingStarted.md ,只是试图理解反DI解决方案。

解决方案

隐式参数足以满足您描述的用例。

 案件类别A(隐含b:B,c:C)
案件类别B(隐含d:D)
案件类别C(隐含d:D)
类D {/ * ... * /}

隐式值theD =新的D
隐式值theB = B()
隐式值theC = C()

现在,您可以通过以下方式要求 A

  val a = A()


I read Dependency Injection Without the Gymnastics PDF which indicates there's no need for any fancy DI framework, but it's beyond my grasp (at least without concrete examples). I'll try watching Dependency Injection Without the Gymnastics and Dead Simple Dependency Injection when I have a chance.

Using Guice in Java, if A depends on both B and C and both B and C depend on D, one would have something like:

public class A {
    @Inject
    public A(B b, C c) {
        this.b = b;
        this.c = c;
    }
}

public class B {
    @Inject
    public B(D d) {
        this.d = d;
    }
}

public class C {
    @Inject
    public C(D d) {
        this.d = d;
    }
}

public class D { /* ... */ }

and a module that says which implementation of D to use, then one would just ask for an instance of A from the injector:

A a = injector.createInstance(A.class);

Given what's presented in the URLs above, how would the Scala-equivalent of the above code look?

FWIW, I'm also investigating https://github.com/dickwall/subcut/blob/master/GettingStarted.md and am simply trying to understand the anti-DI solution.

解决方案

Implicit parameters are completely sufficient for the use case you're describing.

case class A(implicit b: B, c: C)
case class B(implicit d: D)
case class C(implicit d: D)
class D { /* ... */ }

implicit val theD = new D
implicit val theB = B()
implicit val theC = C()

Now you can ask for an A just by:

val a = A()

这篇关于如何避免在Scala中进行依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆