001// Licensed under the Apache License, Version 2.0 (the "License");
002// you may not use this file except in compliance with the License.
003// You may obtain a copy of the License at
004//
005// http://www.apache.org/licenses/LICENSE-2.0
006//
007// Unless required by applicable law or agreed to in writing, software
008// distributed under the License is distributed on an "AS IS" BASIS,
009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010// See the License for the specific language governing permissions and
011// limitations under the License.
012
013package org.apache.tapestry5.ioc.internal.services;
014
015import org.apache.tapestry5.commons.ObjectCreator;
016import org.apache.tapestry5.commons.services.PlasticProxyFactory;
017import org.apache.tapestry5.ioc.ServiceLifecycle;
018import org.apache.tapestry5.ioc.ServiceResources;
019import org.apache.tapestry5.ioc.services.Builtin;
020import org.apache.tapestry5.ioc.services.PerthreadManager;
021
022/**
023 * Allows a service to exist "per thread" (in each thread). Creates a proxy that delegates to a per-thread instance.
024 *
025 * This scheme ensures that, although the service builder method will be invoked many times over the life of the
026 * application, the service decoration process occurs only once. The final calling chain is: Service Proxy -->
027 * Interceptor(s) (from Decorators) --> Advise Proxy (from Advisiors) --> PerThread Proxy --> (per thread)
028 * instance.
029 */
030@SuppressWarnings("all")
031public class PerThreadServiceLifecycle implements ServiceLifecycle
032{
033    private final PerthreadManager perthreadManager;
034
035    private final PlasticProxyFactory proxyFactory;
036
037    public PerThreadServiceLifecycle(@Builtin
038    PerthreadManager perthreadManager,
039
040    @Builtin
041    PlasticProxyFactory proxyFactory)
042    {
043        this.perthreadManager = perthreadManager;
044        this.proxyFactory = proxyFactory;
045    }
046
047    /**
048     * Returns false; this lifecycle represents a service that will be created many times (by each thread).
049     */
050    @Override
051    public boolean isSingleton()
052    {
053        return false;
054    }
055
056    @Override
057    public Object createService(ServiceResources resources, ObjectCreator creator)
058    {
059        ObjectCreator perThreadCreator = perthreadManager.createValue(creator);
060
061        Class serviceInterface = resources.getServiceInterface();
062
063        return proxyFactory.createProxy(serviceInterface, perThreadCreator, "<PerThread Proxy for " + resources.getServiceId() + "(" + serviceInterface.getName() + ")>");
064    }
065}