Pablo
Pablo

Reputation: 3467

Use Guice Factory to create multiple interface implementations but with different dependencies

I would like to know if I can improve the following implementation using Kotlin and Guice

I have a base interface

interface Event {
    val eventInfo
    val eventDate
}

Now I have multiple implementations of this Event, and I'm using assisted injection to create those at runtime

class EventTypeA @Inject constructor(
   @Assisted eventInfo, 
   @Assisted eventDate, 
   @Injected dependency1
): Event {}

class EventTypeB @Inject constructor(
   @Assisted eventInfo, 
   @Assisted eventDate, 
   @Injected dependency2
): Event {}

The guice factory at the moment is looking as follows

interface EventFactory {
   createEventTypeA(@Assisted eventInfo, @Assisted eventDate): EventTypeA
   createEventTypeB(@Assisted eventInfo, @Assisted eventDate): EventTypeB
}

...
configure() {
    install(FactoryModuleBuilder().build(EventFactory::class.java))
}

This works, I can create both types of event by just passing the expected assisted values. Now, what I don't like is that I'm basically repeating the factory signatures over and over again. If I implement 5 different types of event, I'll end up with a factory as follows

interface EventFactory {
   createEventTypeA(@Assisted eventInfo, @Assisted eventDate): EventTypeA
   createEventTypeB(@Assisted eventInfo, @Assisted eventDate): EventTypeB
   createEventTypeC(@Assisted eventInfo, @Assisted eventDate): EventTypeC
   createEventTypeD(@Assisted eventInfo, @Assisted eventDate): EventTypeD
   createEventTypeE(@Assisted eventInfo, @Assisted eventDate): EventTypeE
}

Is there a way to do this in a generic way? Ideally i would like to the factory to leverage a common type or reified while injecting different dependencies. For example:

val eventTypeA = eventFactory<EventTypeA>.create(eventInfo, eventDate)

Feels like it would be much cleaner, while leaving dependency injection to Guice. Been trying to find a solution, but haven't really seen this exact same example on similar posts

Upvotes: 0

Views: 14

Answers (0)

Related Questions