google / google/guice

Allow for scope aliases

Open
#687 1 comment 0 reactions 0 assignees View on GitHub
imported
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

_From [zorzella](https://code.google.com/u/117480957020302471907/) on February 27, 2012 12:10:30_

Let's say I have a:

bindScope(MyScoped.class, new MyScope());

I wish to be able to:

bindScope(MyOtherScoped.class, MyScoped.class);

*****************************************************

Currently, there are a few ways to accomplish something like that (which I list drawbacks here):
1. local var

{
  MyScope myScope = new MyScope();
  bindScope(MyScoped.class, myScope);
  bindScope(MyOtherScoped.class, myScope);
}

Perfect, except this limits things to when both bindScopes are in the same method, which is mostly useless.
1. global static

public static final MyScope MY_SCOPE = new MyScope();

{
  bindScope(MyScoped.class, MY_SCOPE);
}

{
  bindScope(MyOtherScoped.class, MY_SCOPE);
}

This is problematic for Modules.override, and it is also not possible if MyScope is not stateless, and I wish to create multiple injectors in the same JVM. It's also a problem if MyScope's constructor takes a param (not known at static init time).
1. create new instances

{
  bindScope(MyScoped.class, new MyScope());
}

{
  bindScope(MyOtherScoped.class, new MyScope());
}

This is the least problematic one, but it's still inconvenient, particularly if MyScope takes a constructor param that should be shared. It also feels wrong to require multiple instances of the Scope to be created, when all I really wanted was one per injector.
1. Store it in the Module where it's created

class MyModuleA extends AbstractModule {

public final MyScope myScope = new MyScope();

public void configure () {
  bindScope(MyScoped.class, myScope);
}

class MyModuleB extends AbstractModule {

public void configure () {
  MyModuleA a = new MyModuleA();
  install(a);
  bindScope(MyOtherScoped.class, a.myScope);
}

This, though, makes it not possible to install MyModuleA multiple times (see https://code.google.com/p/guiceberry/issues/detail?id=21 ).

*****************************************************

The ideal place to create a scope instance is in a "configure" method. If only I could create aliases to a defined scope annotation as needed, things would be a lot easier.

_Original issue: http://code.google.com/p/google-guice/issues/detail?id=687_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.