dependency injection - How do I use inject a field using a Dagger 2 multi-binding? -
i'm trying support third party extensions using map multibindings, can't wrap head around how it's supposed provide extensible infrastructure. seems should simple, dagger 2 documentation on multibindings doesn't provide example of how it. want other developers able write own implementations of interface provide, , have seamlessly integrate.
here's sample code shows i'm attempting do:
// interface third parties can implement. public interface fooservice { public void run(); } // default implementation of interface provide. class defaultfooimpl implements fooservice { defaultfooimpl() { ... } @override public void run() { ... } } // third parties need add own modules provide // implementations of fooservice on different keys (right?). @module class defaultimplmodule { @provides(type = map) @stringkey("default") static fooservice providedefaultimpl() { return new defaultfooimpl(); } } // problem! won't work third-party implementations, since // can't include modules here because don't know them. @component(modules = defaultimplmodule.class) interface fooservicecomponents { map<string, fooservice> fooservices(); } public class foodispatcher { // problem! how inject map? work? @inject map<string, fooservice> fooservices; void callfooservice(string whichservice) { // whichservice of strings in combined services map. // default implementation, you'd pass in "default". this.fooservices.get(whichservice).run(); } }
so what's missing piece ties , makes work? thanks.
here pattern use - module have configured @ time of using component builder passing arguments. strongly recommend sparing usage , if needed - things should simple need them be, not more :-)
@module class configurablemodule { private idependencyone one; private idependencytwo two; ... configurablemodule() { } configurablemodule(idependencyone one, idependencytwo two, ...) { this.one = one; this.two = two; } @provides idependencyone getidependencyone(myidependencyoneimpl impl) { return 1 == null ? impl : one; } @provides idependencytwo getidependencytwo(myidependencytwoimpl impl) { return 1 == null ? impl : one; } }
Comments
Post a Comment