dimanche 20 octobre 2019

Inject dependency in trait

I have a trait as follows

trait Processor {

  def process(task: Task): Unit
}

object Processor {

  def processTask(taskType: TaskType): Processor = {
    taskType match {
      case Task1         => new TaskProcessor1
      case Task2         => new TaskProcessor2
    }
  }
}

My implementation classes are as follows

class TaskProcessor1 extends Processor {

  override def process(task: Task): Unit = {

  }
}

// and so on

Now, I call this from my service as follows

Processor.processTask(task.taskType).process(task)

and it works perfectly fine.

However, the problem starts when I want to inject Service class in the implementation classes of the trait Processor.

For example

class TaskProcessor1(userService: UserService) extends Processor {

  override def process(task: Task): Unit = {

  }
}

To do so, I inject UserService in trait Processor as follows

trait Processor(userService: UserService) {

      def process(task: Task): Unit
    }

However, this gives a compilation error. Any ideas on how can one inject the UserService in TaskProcessor1. Any pointers will be highly helpful. Thanks in advance !!!

Aucun commentaire:

Enregistrer un commentaire