1

I am trying to inject ehcache via the Play Framework. I am injecting it into a companion class, but that class is being instantiated in an abstract class elsewhere as well as the companion object. I do not want to inject anything into the abstract class because it is being used elsewhere.

For example, this is basically how the companion class and object are set up (removed some logic and extensions for better readability):

class Setting @Inject()(cached: DefaultSyncCacheApi) {
   def isCached(id:String): Boolean = {
       val cachedItem = cached.get(id)
       cachedItem.isDefined
   }
}

object Setting {
   def getId(id:String): Setting = {
      val setting = new Setting //I know this doesn't work
      if (setting.isCached(id)) {
          //retrieval logic
      }
      setting
   }
}

This is the abstract class where it is being instantiated:

abstract class UsingSettingAbstract {
   def methodUsingSetting(): String = {
       val setting = new Setting
       val str = new String
       //logic in here
       str
   }
}

I have tried to create an empty constructor in the Setting class with def this() { }, and creating a chain of constructors, but have so far been unsuccessful in getting the cache to be successfully injected.

I did different versions of below, initializing the cache variable with cached or trying to pass through cached:

class Setting @Inject()(cached: DefaultSyncCacheApi) {
   val cache:DefaultSyncCacheApi
   def this() {
      this(cache)
   }
}

Is there a way to get DI to work with this setup, or would something like a factory pattern work better?

2b2a
  • 95
  • 1
  • 9

1 Answers1

1

With guice you can pass any created instance to the injectors "requestInjection()" method. This will trigger method and field injection on that instance.

So as long as you have access to the injector, you can get injections done.

Jan Galinski
  • 11,768
  • 8
  • 54
  • 77