blob: 65136d32812a8ba9bc4cd4c469a9680b5cedcf31 [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
limpbizkit3d58d6b2008-03-08 16:11:47 +000019import com.google.inject.BindCommandProcessor.CreationListener;
limpbizkit916f5482008-04-16 20:51:14 +000020import com.google.inject.internal.ErrorMessages;
crazyboblee6c7720d2007-03-01 21:49:19 +000021
22/**
23 * Delegates to a custom factory which is also bound in the injector.
24 */
25class BoundProviderFactory<T>
26 implements InternalFactory<T>, CreationListener {
27
28 final Key<? extends Provider<? extends T>> providerKey;
29 final Object source;
30 private InternalFactory<? extends Provider<? extends T>> providerFactory;
31
32 BoundProviderFactory(
33 Key<? extends Provider<? extends T>> providerKey,
34 Object source) {
35 this.providerKey = providerKey;
36 this.source = source;
37 }
38
39 BoundProviderFactory(
40 Key<? extends Provider<? extends T>> providerKey,
41 InternalFactory<? extends Provider<? extends T>> providerFactory,
42 Object source) {
43 this.providerKey = providerKey;
44 this.providerFactory = providerFactory;
45 this.source = source;
46 }
47
48 public void notify(final InjectorImpl injector) {
49 injector.withDefaultSource(source, new Runnable() {
50 public void run() {
crazyboblee712705c2007-09-07 03:20:30 +000051 providerFactory = injector.getInternalFactory(providerKey);
crazyboblee6c7720d2007-03-01 21:49:19 +000052 }
53 });
54 }
55
56 public String toString() {
57 return providerKey.toString();
58 }
59
limpbizkitfcf2b8c2007-10-21 18:23:43 +000060 public T get(InternalContext context, InjectionPoint<?> injectionPoint) {
61 Provider<? extends T> provider = providerFactory.get(context, injectionPoint);
limpbizkit1dabcfd2007-08-25 08:06:30 +000062 try {
limpbizkitfcf2b8c2007-10-21 18:23:43 +000063 return injectionPoint.checkForNull(provider.get(), source);
limpbizkitb946ca22007-08-25 15:56:50 +000064 } catch(ProvisionException e) {
65 throw e;
limpbizkit1dabcfd2007-08-25 08:06:30 +000066 } catch(RuntimeException e) {
limpbizkitfcf2b8c2007-10-21 18:23:43 +000067 throw new ProvisionException(e, ErrorMessages.ERROR_IN_PROVIDER);
limpbizkit1dabcfd2007-08-25 08:06:30 +000068 }
crazyboblee6c7720d2007-03-01 21:49:19 +000069 }
70}