Complex model with AssistedInject

47 views
Skip to first unread message

Guy Gadon

unread,
Dec 2, 2014, 3:15:27 PM12/2/14
to google...@googlegroups.com
Hello!
I'm trying to figure out a solution for this problem:
Let's say I have these classes:

public class A {
@Inject
A(@Assisted String param){
...
}
}

public class B{
@Inject
B(@Assisted A) {
...
}
}

Now I would like to create a factory of class B, that will get the parameter of A as the parameter of the factory's create method.
Is there a way of doing this without creating another level of abstraction? (The another level would be to create my own factory that uses both A's and B's factories...)

It is important to say that I don't want to pass parameter of class A to class B, it breaks the point of guice in a way.

I've searched in some places, and saw some references about scoping, and bypassing the problem in some ways, but nothing was actually useful.

Thank you in advance :)

Sam Berlin

unread,
Dec 2, 2014, 3:49:20 PM12/2/14
to google...@googlegroups.com

Sounds like you want to build something custom that doesn't come out of the box. Shouldn't be hard to create your own factory implementation.

sam


--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice+unsubscribe@googlegroups.com.
To post to this group, send email to google...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-guice.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-guice/9da20dbe-3a8c-46ac-9eb3-30264edf6f3f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Guy Gadon

unread,
Dec 3, 2014, 12:38:29 AM12/3/14
to google...@googlegroups.com
I tried to avoid that, but I guess there is no choice.. It just that it feels like an overkill to create a factory that uses guice's factories in order to create a simple object.

Thank you anyway :)

Tushar Bhasme

unread,
Dec 3, 2014, 3:06:57 AM12/3/14
to google...@googlegroups.com
This is how it should be done (ref):

When you create A with assisted injection, you would need to also provide an interface to create instance of A:
class A {
    interface AFactory {
        A create(String param)
    }

    public A(@Assisted String param) {... }
    ...
}

You would then bind the factory in your module:
install(new FactoryModuleBuilder()
     .implement(A.class)
     .build(AFactory.class));

In B, to create A, you should inject AFactory and NOT A:
class B {
    private A a;

    public B(AFactory factory) {
        this.a = factory.create("param");
    }
}


Thanks,
Tushar
Reply all
Reply to author
Forward
0 new messages