google / google/guice

Keyed providers

Open
#211 3 comments 0 reactions 0 assignees View on GitHub
Component-Unknown enhancement imported Priority-Medium
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

_From [bslesinsky](https://code.google.com/u/bslesinsky/) on June 18, 2008 19:56:16_

I was thinking about how something like conversation scope would work with
partial injection, and came up with this example showing how a User scope
could work:

configure() {
  bind(UserPrefs.class).withKey(UserKey.class).toKeyedProvider(...)
}

class UserSpecificView {
  `@`Inject
  UserPrefs prefs;
  ...
}

class ViewUsingClass {
  `@`Inject
  KeyedProvider<UserKey, UserSpecificView> viewSource;

  void handleRequest(UserKey userKey) {
    UserSpecificView view = viewSource.get(userKey);
  }
}

The basic idea is that Guice should allow modules to bind providers that
add another dimension in the injector map.  Guice would need to get
involved because the module implements a provider from UserKey to
UserPrefs, but the ViewUsingClass wants a provider from UserKey to
UserSpecificView.  Guice would automatically create the intermediate provider.

Compared to something like request scope, I think this is actually
preferable because you can tell from handleRequest that it is called from
*outside* User scope but can create objects that are *inside* User scope,
because it takes UserKey as an argument.  Only instances that are created
inside User scope could have a zero-argument handleRequest() method,
because they can have the UserKey (or any other UserKey-scope class)
injected into them.

To my way of thinking, this is better than a thread-local because it
clearly distinguishes methods that run inside versus outside a scope.  For
methods that run outside a scope, it also allows you to control which scope
is used by passing a different key.

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

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.