【问题标题】:Scala PlayFramework how can I inject repository method inside functionScala PlayFramework如何在函数中注入存储库方法
【发布时间】:2016-05-27 23:26:49
【问题描述】:

我正在使用播放框架版本 2.49,我正在尝试进行依赖注入,这是我第一次这样做。我有 3 个文件夹接口:存储库:控制器。该接口列出了我在存储库文件夹中实现的抽象方法,然后注入到控制器操作中。我只在涉及控制器操作时迷路了。这是一个地雷示例代码

界面

package Interface


abstract class Iprofiles {
  def edit_profile
  def view_profile
  def forgot_password

}

存储库

package Repository

import Interface.Iprofiles
import slick.driver.PostgresDriver.api._

class ProfileRepository extends Iprofiles  {
  val db= Database.forConfig("database")

// These 3 methods will have Database logic soon
  def edit_profile: Unit
  def view_profile: Unit

  def forgot_password: Unit 
}

控制器

package controllers

import play.api.data.Form
import play.api.data.Forms._
class Relations extends Controller {


  def MyAction() = Action {
 // How can I inject edit_profile in the repository folder here
Ok()

}



}

我的存储库方法现在是空的,但我很快就会在其中包含数据逻辑。例如,在我的控制器 MyAction() 方法中,如何执行 DI 并从存储库文件夹中包含 edit_profile ?我一直在寻找如何完成这项工作,但没有任何效果

【问题讨论】:

  • 最近几天我一直在研究 Play 中的 DI(主要使用 Guice),我的理解是,推荐的方法是通过构造函数而不是方法注入依赖项。你能接受吗?

标签: scala playframework dependency-injection playframework-2.3


【解决方案1】:

JVM 上的依赖注入目前只涉及注入对象引用,而不是方法引用。也就是说,在一个类中,你声明一个类型(通常是一个接口)的依赖关系,并在注入器配置中定义从这个(接口)类型到实现(类型)的映射。 在注入期间 - 通常在对象构造期间 - 您会获得对注入实现类型的对象的引用。

然后您可以调用该注入对象的所有方法。

所以你需要一个获取引用的属性,这通常通过构造函数参数填充。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多