Search code examples
scaladependency-injectionguice

Why there is need to provide injected arguments while creating object of class?


I have a doubt related to dependency injection using Google Guice.

I have a trait which has few implemented methods

trait ATrait {
    def someMethodA(parameters: ArgType) = {
     //code
    }

    def someMethodB(parameters: ArgType) = {
     //code
    }
}    
object A extends ATrait

Now I have a class B, where I need methods of Atrait. So I have injected it.

class B @Inject(a: ATrait) {
  //code
}

I have also given the binding in Guice module class.

class GuiceModule extends AbstractModule {
  override def configure(): Unit = {
    bind[ATrait].toInstance(A)
  }
}

Now when I create an object of class B,

val b = new B()

It won't let me do that, so my question is if I have to pass manually object of ATrait. What is the use of Google Guice Injection?

I might have done some mistake because I am learning this. Please guide me if I have not understood something correctly.

Thanks in advance.


Solution

  • Guice doesn't work in that way. If you want a new root object you need to ask Guice for a new instance.

    val injector = Guice.createInjector(new GuiceModule())
    
    val a:ATrait = injector.getInstance(classOf[ATrait])