blob: c08786caa528ddbc6ef5ae7f1233feabe36f333a [file] [log] [blame]
limpbizkit76c24b12008-12-25 04:32:41 +00001/**
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;
18
19import com.google.inject.internal.BindingImpl;
20import com.google.inject.internal.Errors;
21import com.google.inject.internal.ErrorsException;
22import com.google.inject.internal.InternalContext;
23import com.google.inject.internal.InternalFactory;
24import com.google.inject.spi.Dependency;
limpbizkitc3f92842008-12-30 19:43:47 +000025import com.google.inject.spi.PrivateElements;
limpbizkit76c24b12008-12-25 04:32:41 +000026
limpbizkitc3f92842008-12-30 19:43:47 +000027/**
28 * This factory exists in a parent injector. When invoked, it retrieves its value from a child
29 * injector.
30 */
limpbizkit76c24b12008-12-25 04:32:41 +000031class ExposedKeyFactory<T> implements InternalFactory<T>, BindingProcessor.CreationListener {
32 private final Key<T> key;
limpbizkitc3f92842008-12-30 19:43:47 +000033 private final PrivateElements privateElements;
limpbizkit76c24b12008-12-25 04:32:41 +000034 private BindingImpl<T> delegate;
35
limpbizkitc3f92842008-12-30 19:43:47 +000036 public ExposedKeyFactory(Key<T> key, PrivateElements privateElements) {
limpbizkit76c24b12008-12-25 04:32:41 +000037 this.key = key;
limpbizkitc3f92842008-12-30 19:43:47 +000038 this.privateElements = privateElements;
limpbizkit76c24b12008-12-25 04:32:41 +000039 }
40
limpbizkitc3f92842008-12-30 19:43:47 +000041 public void notify(Errors errors) {
42 InjectorImpl privateInjector = (InjectorImpl) privateElements.getInjector();
limpbizkit76c24b12008-12-25 04:32:41 +000043 BindingImpl<T> explicitBinding = privateInjector.state.getExplicitBinding(key);
44
limpbizkitc3f92842008-12-30 19:43:47 +000045 // validate that the child injector has its own factory. If the getInternalFactory() returns
46 // this, then that child injector doesn't have a factory (and getExplicitBinding has returned
47 // its parent's binding instead
limpbizkit76c24b12008-12-25 04:32:41 +000048 if (explicitBinding.getInternalFactory() == this) {
49 errors.withSource(explicitBinding.getSource()).exposedButNotBound(key);
50 return;
51 }
52
53 this.delegate = explicitBinding;
54 }
55
56 public T get(Errors errors, InternalContext context, Dependency<?> dependency)
57 throws ErrorsException {
58 return delegate.getInternalFactory().get(errors, context, dependency);
59 }
60}