blob: 3cbfc11888be0ba9346f3c00109ee6819f6d54f6 [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;
limpbizkit3b1cd582008-04-28 00:06:01 +000021import com.google.inject.internal.ResolveFailedException;
crazyboblee6c7720d2007-03-01 21:49:19 +000022
23/**
24 * Delegates to a custom factory which is also bound in the injector.
25 */
26class BoundProviderFactory<T>
27 implements InternalFactory<T>, CreationListener {
28
29 final Key<? extends Provider<? extends T>> providerKey;
30 final Object source;
31 private InternalFactory<? extends Provider<? extends T>> providerFactory;
32
33 BoundProviderFactory(
34 Key<? extends Provider<? extends T>> providerKey,
35 Object source) {
36 this.providerKey = providerKey;
37 this.source = source;
38 }
39
crazyboblee6c7720d2007-03-01 21:49:19 +000040 public void notify(final InjectorImpl injector) {
41 injector.withDefaultSource(source, new Runnable() {
42 public void run() {
limpbizkit3b1cd582008-04-28 00:06:01 +000043 try {
44 providerFactory = injector.getInternalFactory(providerKey);
45 } catch (ResolveFailedException e) {
46 injector.errorHandler.handle(source, e.getMessage());
47 }
crazyboblee6c7720d2007-03-01 21:49:19 +000048 }
49 });
50 }
51
limpbizkitfcf2b8c2007-10-21 18:23:43 +000052 public T get(InternalContext context, InjectionPoint<?> injectionPoint) {
53 Provider<? extends T> provider = providerFactory.get(context, injectionPoint);
limpbizkit1dabcfd2007-08-25 08:06:30 +000054 try {
limpbizkitfcf2b8c2007-10-21 18:23:43 +000055 return injectionPoint.checkForNull(provider.get(), source);
limpbizkitb946ca22007-08-25 15:56:50 +000056 } catch(ProvisionException e) {
57 throw e;
limpbizkit1dabcfd2007-08-25 08:06:30 +000058 } catch(RuntimeException e) {
limpbizkitfcf2b8c2007-10-21 18:23:43 +000059 throw new ProvisionException(e, ErrorMessages.ERROR_IN_PROVIDER);
limpbizkit1dabcfd2007-08-25 08:06:30 +000060 }
crazyboblee6c7720d2007-03-01 21:49:19 +000061 }
limpbizkitc9465f92008-05-31 19:01:54 +000062
63 @Override public String toString() {
64 return providerKey.toString();
65 }
crazyboblee6c7720d2007-03-01 21:49:19 +000066}