4

我有一个包含子应用程序的应用程序。我想隔离 GIN 注入,以便每个子应用程序可以具有相同核心共享类的单独实例。我还希望注入器将一些核心模块的类提供给所有子应用程序,以便可以共享单例实例。例如

GIN Modules:
  Core - shared
  MetadataCache - one per sub-application
  UserProvider - one per sub-application

在 Guice 我可以使用 来做到这一点createChildInjector,但我在 GIN 中看不到明显的等价物。

我可以在 GIN 中实现类似的东西吗?

4

2 回答 2

4

感谢@Abderrazakk 提供的链接,我解决了这个问题,但是由于链接不是很及时的说明,我想我也会在这里添加一个示例解决方案:

私有 GIN 模块允许您进行单级分层注入,其中在私有模块中注册的类型仅对该模块中创建的其他实例可见。在任何非私有模块中注册的类型仍然可供所有人使用。

例子

让我们有一些样本类型来注入(和注入):

public class Thing {
    private static int thingCount = 0;
    private int index;

    public Thing() {
        index = thingCount++;
    }

    public int getIndex() {
        return index;
    }
}

public class SharedThing extends Thing {
}

public class ThingOwner1 {
    private Thing thing;
    private SharedThing shared;

    @Inject
    public ThingOwner1(Thing thing, SharedThing shared) {
        this.thing = thing;
        this.shared = shared;
    }

    @Override
    public String toString() {
        return "" + this.thing.getIndex() + ":" + this.shared.getIndex();
    }
}

public class ThingOwner2 extends ThingOwner1 {
    @Inject
    public ThingOwner2(Thing thing, SharedThing shared) {
        super(thing, shared);
    }
}

像这样创建两个私有模块(第二个使用 ThingOwner2):

public class MyPrivateModule1 extends PrivateGinModule {
  @Override
  protected void configure() {
    bind(Thing.class).in(Singleton.class);
    bind(ThingOwner1.class).in(Singleton.class);
  }
}

和一个共享模块:

public class MySharedModule extends AbstractGinModule {
    @Override
    protected void configure() {
        bind(SharedThing.class).in(Singleton.class);
    }
}

现在在我们的注入器中注册两个模块:

@GinModules({MyPrivateModule1.class, MyPrivateModule2.class, MySharedModule.class})
public interface MyGinjector extends Ginjector {
    ThingOwner1 getOwner1();
    ThingOwner2 getOwner2();
}

最后,我们可以看到 ThingOwner1 和 ThingOwner2 实例都具有来自共享模块的相同 SharedThing 实例,但来自其私有注册的不同 Thing 实例:

System.out.println(injector.getOwner1().toString());
System.out.println(injector.getOwner2().toString());
于 2012-01-27T14:01:12.637 回答
2

这是在 SOF http://code.google.com/p/google-gin/wiki/PrivateModulesDesignDoc上。希望它可以帮助你。

于 2012-01-26T15:55:33.823 回答