blob: f0708e092cbd5fd6648880e61fd8f8462a8d3031 [file] [log] [blame]
crazyboblee6c7720d2007-03-01 21:49:19 +00001/**
2 * Copyright (C) 2006 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.BinderImpl.CreationListener;
20
21/**
22 * Delegates to a custom factory which is also bound in the injector.
23 */
24class BoundProviderFactory<T>
25 implements InternalFactory<T>, CreationListener {
26
27 final Key<? extends Provider<? extends T>> providerKey;
28 final Object source;
29 private InternalFactory<? extends Provider<? extends T>> providerFactory;
30
31 BoundProviderFactory(
32 Key<? extends Provider<? extends T>> providerKey,
33 Object source) {
34 this.providerKey = providerKey;
35 this.source = source;
36 }
37
38 BoundProviderFactory(
39 Key<? extends Provider<? extends T>> providerKey,
40 InternalFactory<? extends Provider<? extends T>> providerFactory,
41 Object source) {
42 this.providerKey = providerKey;
43 this.providerFactory = providerFactory;
44 this.source = source;
45 }
46
47 public void notify(final InjectorImpl injector) {
48 injector.withDefaultSource(source, new Runnable() {
49 public void run() {
crazyboblee712705c2007-09-07 03:20:30 +000050 providerFactory = injector.getInternalFactory(providerKey);
crazyboblee6c7720d2007-03-01 21:49:19 +000051 }
52 });
53 }
54
55 public String toString() {
56 return providerKey.toString();
57 }
58
limpbizkitfcf2b8c2007-10-21 18:23:43 +000059 public T get(InternalContext context, InjectionPoint<?> injectionPoint) {
60 Provider<? extends T> provider = providerFactory.get(context, injectionPoint);
limpbizkit1dabcfd2007-08-25 08:06:30 +000061 try {
limpbizkitfcf2b8c2007-10-21 18:23:43 +000062 return injectionPoint.checkForNull(provider.get(), source);
limpbizkitb946ca22007-08-25 15:56:50 +000063 } catch(ProvisionException e) {
64 throw e;
limpbizkit1dabcfd2007-08-25 08:06:30 +000065 } catch(RuntimeException e) {
limpbizkitfcf2b8c2007-10-21 18:23:43 +000066 throw new ProvisionException(e, ErrorMessages.ERROR_IN_PROVIDER);
limpbizkit1dabcfd2007-08-25 08:06:30 +000067 }
crazyboblee6c7720d2007-03-01 21:49:19 +000068 }
69}