Guice runtime dependency parameters reinjection

只谈情不闲聊 提交于 2019-12-03 08:14:58

MPierce - agreed. Ill try to explain the way i visualized the problem(you can correct me if im wrong).

Being originaly derived from a "service locator" pattern, the idea that it can manage more than services is optimistic to say the least.

We could split the application into Service and Data classes, or you could say that we have application and infrastructure code - "Dependency Injection", a great book.

So, basicly, dependecy injection, and dependency injection frameworks in general are great. For solving infrastructure, or "service" code.

Any dynamic(runtime) parameters being injected into the Container/Injector are basicly forcing you to end the object graph.

For example, we have the folowing design:

EmailMessage is a runtime parameter. It can be "injected" into email service outside the Container/Injector, but it ends the object graph. If we want to request EmailDispatcher, after we injected the EmailMessage into EmailService(which is, I repeat, done outside injector), we could no longer fetch EmailDispatcher from the injector.

Then, you could redesign your model so it "fits" into the Container/Injector concept of dynamic parameters.

But then again, you forced the design, and suddenly, EmailDispatcher has too many responsibilites. It could be used in such a context, where you dont have many infrastructure classes.

And when you have a design like you have in the third example picture, you cannot use the Injector/Container to fetch you a NextService3 instance(nor any below the level of EmailDispatcher).

The problem being - if you have any dynamic(runtime) parameters, you can only use dependency injection for classes above the class that requires a dynamic parameter, you can forget the classes below.

Phew.

Correct?

Part of the problem depends on how you're resolving that 'false' is the thing you want to set for the leash field. Is that coming from config data or what?

A provider method may be helpful...

class FooModule extends AbstractModule {
...
    @Provides
    Walkable getWalkable(Dog dog) {
        boolean leash = getBooleanFromSomewhere();
        return new Walk(dog, leash);
    }
}

If you can clarify where that boolean is coming from, it'll help me to understand what type of approach is applicable.

You can use custom scopes, much like when using guice servlets. That way you can create your instance, and then seed it in the injector.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!