1/**
2 * Copyright (C) 2008 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.inject.internal;
18
19import com.google.inject.Key;
20import com.google.inject.spi.Dependency;
21import com.google.inject.spi.PrivateElements;
22
23/**
24 * This factory exists in a parent injector. When invoked, it retrieves its value from a child
25 * injector.
26 */
27final class ExposedKeyFactory<T> implements InternalFactory<T>, CreationListener {
28  private final Key<T> key;
29  private final PrivateElements privateElements;
30  private BindingImpl<T> delegate;
31
32  ExposedKeyFactory(Key<T> key, PrivateElements privateElements) {
33    this.key = key;
34    this.privateElements = privateElements;
35  }
36
37  public void notify(Errors errors) {
38    InjectorImpl privateInjector = (InjectorImpl) privateElements.getInjector();
39    BindingImpl<T> explicitBinding = privateInjector.state.getExplicitBinding(key);
40
41    // validate that the child injector has its own factory. If the getInternalFactory() returns
42    // this, then that child injector doesn't have a factory (and getExplicitBinding has returned
43    // its parent's binding instead
44    if (explicitBinding.getInternalFactory() == this) {
45      errors.withSource(explicitBinding.getSource()).exposedButNotBound(key);
46      return;
47    }
48
49    this.delegate = explicitBinding;
50  }
51
52  public T get(Errors errors, InternalContext context, Dependency<?> dependency, boolean linked)
53      throws ErrorsException {
54    return delegate.getInternalFactory().get(errors, context, dependency, linked);
55  }
56}
57