blob: 61046a1b7a39a9b6aa0f1ecea1ecc2d96a936a0e [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() {
50 providerFactory = injector.getInternalFactory(null, providerKey);
51 }
52 });
53 }
54
55 public String toString() {
56 return providerKey.toString();
57 }
58
59 public T get(InternalContext context) {
limpbizkit1dabcfd2007-08-25 08:06:30 +000060 Provider<? extends T> provider = providerFactory.get(context);
61 try {
62 return context.sanitize(provider.get(), source);
63 } catch(ProvisionException provisionException) {
64 provisionException.addContext(context.getExternalContext());
65 throw provisionException;
66 } catch(RuntimeException e) {
67 throw new ProvisionException(context.getExternalContext(), e,
68 ErrorMessages.ERROR_IN_PROVIDER);
69 }
crazyboblee6c7720d2007-03-01 21:49:19 +000070 }
71}