You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@isis.apache.org by ah...@apache.org on 2018/12/19 07:17:57 UTC

[isis] branch v2 updated: ISIS-2033: proper support for CDI lifecycle

This is an automated email from the ASF dual-hosted git repository.

ahuber pushed a commit to branch v2
in repository https://gitbox.apache.org/repos/asf/isis.git


The following commit(s) were added to refs/heads/v2 by this push:
     new 08896e1  ISIS-2033: proper support for CDI lifecycle
08896e1 is described below

commit 08896e1cb000c75d7fe7bd2e630b48ce66e58032
Author: Andi Huber <ah...@apache.org>
AuthorDate: Wed Dec 19 08:17:47 2018 +0100

    ISIS-2033: proper support for CDI lifecycle
    
    
    Task-Url: https://issues.apache.org/jira/browse/ISIS-2033
---
 .../org/apache/isis/commons/internal/cdi/_CDI.java | 65 ++++++++++++----
 .../isis/commons/internal/cdi/_CDI_Lifecycle.java  | 48 ++++++++++++
 .../commons/internal/exceptions/_Exceptions.java   | 11 ++-
 .../org/apache/isis/config/AppConfigLocator.java   | 19 +++++
 .../config/internal/_Config_LifecycleResource.java |  2 +-
 .../isis/tool/mavenplugin/IsisMojoAbstract.java    |  2 +-
 .../isis/core/runtime/headless/IsisSystem.java     |  2 +-
 .../core/runtime/system/context/IsisContext.java   | 32 +++++---
 .../runtime/system/session/IsisInjectModule.java   | 75 ------------------
 .../runtime/system/session/IsisSessionFactory.java | 80 ++++++++++---------
 .../system/session/IsisSessionFactoryBuilder.java  | 22 ++----
 .../core/webapp/IsisWebAppContextListener.java     | 25 +++---
 .../wicket/viewer/IsisWicketApplication.java       | 21 +----
 .../integration/wicket/WebRequestCycleForIsis.java |  5 +-
 .../isisWicketModule_bindingsStandard_Test.java    | 91 ----------------------
 15 files changed, 220 insertions(+), 280 deletions(-)

diff --git a/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI.java b/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI.java
index dc56eb6..0166fe7 100644
--- a/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI.java
+++ b/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI.java
@@ -25,14 +25,19 @@ import java.util.function.Supplier;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
+import javax.enterprise.inject.spi.BeanManager;
 import javax.enterprise.inject.spi.CDI;
+import javax.enterprise.inject.spi.CDIProvider;
 import javax.inject.Qualifier;
 
+import org.apache.isis.commons.internal.context._Context;
 import org.apache.isis.commons.internal.exceptions._Exceptions;
+import org.apache.isis.commons.internal.functions._Functions.CheckedRunnable;
 import org.apache.isis.core.plugins.ioc.IocPlugin;
 
 import static org.apache.isis.commons.internal.base._NullSafe.isEmpty;
 import static org.apache.isis.commons.internal.base._NullSafe.stream;
+import static org.apache.isis.commons.internal.base._With.requires;
 
 /**
  * <h1>- internal use only -</h1>
@@ -45,20 +50,45 @@ import static org.apache.isis.commons.internal.base._NullSafe.stream;
  * @since 2.0.0-M2
  */
 public final class _CDI {
-    
+
+    /**
+     * Bootstrap CDI if not already present.
+     * @param onDiscover - Packages of the specified (stream of) classes will be scanned and found classes 
+     * will be added to the set of bean classes for the synthetic bean archive. 
+     */
     public static void init(Supplier<Stream<Class<?>>> onDiscover) {
         
         if(cdi().isPresent()) {
             return;
         }
         
-        CDI.setCDIProvider(IocPlugin.get().getCDIProvider(onDiscover.get()));
+        requires(onDiscover, "onDiscover");
+        
+        // plug in the provider
+        final CDIProvider standaloneCDIProvider = IocPlugin.get().getCDIProvider(onDiscover.get());
+        CDI.setCDIProvider(standaloneCDIProvider);
 
         // verify
         if(!cdi().isPresent()) {
-            throw _Exceptions.unexpectedCodeReach();
+            throw _Exceptions.unrecoverable("Could not resolve an instance of CDI.");
         }
         
+        // proper CDI lifecycle support utilizing the fact that WELD provides a WeldContainer that 
+        // implements AutoCloseable, which we can put on the _Context, such that when _Context.clear()
+        // is called, gets properly closed
+        final CheckedRunnable onClose = () -> ((AutoCloseable)CDI.current()).close();
+        _Context.putSingleton(_CDI_Lifecycle.class, _CDI_Lifecycle.of(onClose));
+        
+    }
+    
+    /**
+     * Get the CDI BeanManager for the current context.
+     * @return non-null
+     * @throws RuntimeException - if no BeanManager could be resolved
+     */
+    public static BeanManager getBeanManager() {
+        return cdi().map(CDI::getBeanManager)
+                .orElseThrow(()->_Exceptions.unrecoverable("Could not resolve a BeanManager."));
     }
     
     
@@ -95,19 +125,6 @@ public final class _CDI {
     }
     
     /**
-     * Get the CDI instance that provides access to the current container. 
-     * @return an optional
-     */
-    public static Optional<CDI<Object>> cdi() {
-        try {
-            CDI<Object> cdi = CDI.current();
-            return Optional.ofNullable(cdi);
-        } catch (Exception e) {
-            return Optional.empty();
-        }
-    }
-
-    /**
      * Filters the input array into a collection, such that only annotations are retained, 
      * that are valid qualifiers for CDI.
      * @param annotations
@@ -134,6 +151,19 @@ public final class _CDI {
     
     private _CDI() {}
     
+    /**
+     * Get the CDI instance that provides access to the current container. 
+     * @return an optional
+     */
+    private static Optional<CDI<Object>> cdi() {
+        try {
+            CDI<Object> cdi = CDI.current();
+            return Optional.ofNullable(cdi);
+        } catch (Exception e) {
+            return Optional.empty();
+        }
+    }
+    
     private static <T> T tryGet(final Supplier<T> supplier) {
         try { 
             return supplier.get();  
@@ -142,4 +172,7 @@ public final class _CDI {
         }
     }
 
+
+
+
 }
diff --git a/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI_Lifecycle.java b/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI_Lifecycle.java
new file mode 100644
index 0000000..7e13f8e
--- /dev/null
+++ b/core/commons/src/main/java/org/apache/isis/commons/internal/cdi/_CDI_Lifecycle.java
@@ -0,0 +1,48 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.isis.commons.internal.cdi;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.isis.commons.internal.functions._Functions.CheckedRunnable;
+
+import lombok.RequiredArgsConstructor;
+import lombok.val;
+
+@RequiredArgsConstructor(staticName="of")
+final class _CDI_Lifecycle implements AutoCloseable {
+
+    private static final Logger LOG = LoggerFactory.getLogger(_CDI_Lifecycle.class);
+    
+    private final CheckedRunnable onClose;
+    
+    @Override
+    public void close() {
+        try {
+            onClose.run();
+        } catch (Exception e) {
+            val note = "This implementation expects the IocPlugin to provide a CDIProvider "
+                    + "that creates CDI instances that implement AutoClosable";
+            
+            LOG.warn("Failed to properly close the CDI container. Note: {}", note, e);
+        }
+    }
+    
+}
diff --git a/core/commons/src/main/java/org/apache/isis/commons/internal/exceptions/_Exceptions.java b/core/commons/src/main/java/org/apache/isis/commons/internal/exceptions/_Exceptions.java
index c2c4a80..7365047 100644
--- a/core/commons/src/main/java/org/apache/isis/commons/internal/exceptions/_Exceptions.java
+++ b/core/commons/src/main/java/org/apache/isis/commons/internal/exceptions/_Exceptions.java
@@ -83,7 +83,15 @@ public final class _Exceptions {
     }
     
     public static RuntimeException unrecoverable(Exception cause) {
-        return new RuntimeException("internal error: unrecoverable error with cause ...", cause);
+        return new RuntimeException("unrecoverable error: with cause ...", cause);
+    }
+    
+    public static RuntimeException unrecoverable(String msg) {
+        return new RuntimeException(String.format("unrecoverable error: '%s'", msg));
+    }
+    
+    public static RuntimeException unrecoverable(String msg, Exception cause) {
+        return new RuntimeException(String.format("unrecoverable error: '%s' with cause ...", msg), cause);
     }
     
     /**
@@ -317,6 +325,7 @@ public final class _Exceptions {
         }
     }
 
+
     
 
 
diff --git a/core/config/src/main/java/org/apache/isis/config/AppConfigLocator.java b/core/config/src/main/java/org/apache/isis/config/AppConfigLocator.java
index be4b544..00283c6 100644
--- a/core/config/src/main/java/org/apache/isis/config/AppConfigLocator.java
+++ b/core/config/src/main/java/org/apache/isis/config/AppConfigLocator.java
@@ -1,3 +1,19 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
 package org.apache.isis.config;
 
 import org.slf4j.Logger;
@@ -11,6 +27,9 @@ import org.apache.isis.commons.internal.context._Plugin;
 import org.apache.isis.config.builder.IsisConfigurationBuilder;
 import org.apache.isis.core.commons.exceptions.IsisException;
 
+/**
+ * @since 2.0.0-M2
+ */
 public final class AppConfigLocator {
     
     private static final Logger LOG = LoggerFactory.getLogger(AppConfigLocator.class);
diff --git a/core/config/src/main/java/org/apache/isis/config/internal/_Config_LifecycleResource.java b/core/config/src/main/java/org/apache/isis/config/internal/_Config_LifecycleResource.java
index aef3c66..3ee9d00 100644
--- a/core/config/src/main/java/org/apache/isis/config/internal/_Config_LifecycleResource.java
+++ b/core/config/src/main/java/org/apache/isis/config/internal/_Config_LifecycleResource.java
@@ -62,7 +62,7 @@ class _Config_LifecycleResource {
         }
         
         // Logging in the context of IsisConfiguration
-        LoggerFactory.getLogger(IsisConfiguration.class).info("=== BUILT/DONE ===");
+        LoggerFactory.getLogger(IsisConfiguration.class).info("Configuration is final.");
         
         return builder.build();
         
diff --git a/core/maven-plugin/src/main/java/org/apache/isis/tool/mavenplugin/IsisMojoAbstract.java b/core/maven-plugin/src/main/java/org/apache/isis/tool/mavenplugin/IsisMojoAbstract.java
index 0adc1a4..302a33b 100644
--- a/core/maven-plugin/src/main/java/org/apache/isis/tool/mavenplugin/IsisMojoAbstract.java
+++ b/core/maven-plugin/src/main/java/org/apache/isis/tool/mavenplugin/IsisMojoAbstract.java
@@ -76,7 +76,7 @@ public abstract class IsisMojoAbstract extends AbstractMojo {
         
         IsisSessionFactory isisSessionFactory = null;
         try {
-            isisSessionFactory = isisSessionFactoryBuilder.buildSessionFactory();
+            isisSessionFactory = isisSessionFactoryBuilder.buildSessionFactory(IsisSessionFactory::new);
             if(!isisSessionFactoryBuilder.isMetaModelValid()) {
                 MetaModelInvalidException metaModelInvalidException = IsisContext
                         .getMetaModelInvalidExceptionIfAny();
diff --git a/core/runtime/src/main/java/org/apache/isis/core/runtime/headless/IsisSystem.java b/core/runtime/src/main/java/org/apache/isis/core/runtime/headless/IsisSystem.java
index 25c122b..6417f58 100644
--- a/core/runtime/src/main/java/org/apache/isis/core/runtime/headless/IsisSystem.java
+++ b/core/runtime/src/main/java/org/apache/isis/core/runtime/headless/IsisSystem.java
@@ -128,7 +128,7 @@ public final class IsisSystem {
             // ensures that a FixtureClock is installed as the singleton underpinning the ClockService
             FixtureClock.initialize();
 
-            isisSessionFactory = isisSessionFactoryBuilder.buildSessionFactory();
+            isisSessionFactory = isisSessionFactoryBuilder.buildSessionFactory(IsisSessionFactory::new);
             // REVIEW: does no harm, but is this required?
             closeSession();
 
diff --git a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/context/IsisContext.java b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/context/IsisContext.java
index 4570a76..78151aa 100644
--- a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/context/IsisContext.java
+++ b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/context/IsisContext.java
@@ -57,18 +57,18 @@ public interface IsisContext {
         return _Context.getIfAny(MetaModelInvalidException.class);
     }
 
-    /**
-     *
-     * @return Isis's session factory
-     * @throws IllegalStateException if IsisSessionFactory not initialized
-     */
-    // Implementation Note: Populated only by {@link IsisSessionFactoryBuilder}.
-    public static IsisSessionFactory getSessionFactory() {
-        return _Context.getOrThrow(
-                IsisSessionFactory.class,
-                ()->new IllegalStateException(
-                        "internal error: should have been populated by IsisSessionFactoryBuilder") );
-    }
+//    /**
+//     *
+//     * @return Isis's session factory
+//     * @throws IllegalStateException if IsisSessionFactory not initialized
+//     */
+//    // Implementation Note: Populated only by {@link IsisSessionFactoryBuilder}.
+//    public static IsisSessionFactory getSessionFactory() {
+//        return _Context.getOrThrow(
+//                IsisSessionFactory.class,
+//                ()->new IllegalStateException(
+//                        "internal error: should have been populated by IsisSessionFactoryBuilder") );
+//    }
 
     /**
      *
@@ -155,6 +155,14 @@ public interface IsisContext {
     }
     
     /**
+     * @return framework's IsisSessionFactory
+     * @throws NoSuchElementException - if IsisSessionFactory not managed
+     */
+    public static IsisSessionFactory getSessionFactory() {
+        return _CDI.getManagedBean(IsisSessionFactory.class).get();
+    }
+    
+    /**
      * @return framework's ServicesInjector
      * @throws NullPointerException - if AppManifest is null
      */
diff --git a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisInjectModule.java b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisInjectModule.java
deleted file mode 100644
index 9b69400..0000000
--- a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisInjectModule.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.isis.core.runtime.system.session;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.inject.Produces;
-import javax.inject.Inject;
-
-import org.apache.isis.config.IsisConfiguration;
-import org.apache.isis.core.metamodel.services.ServicesInjector;
-import org.apache.isis.core.metamodel.specloader.SpecificationLoader;
-import org.apache.isis.core.runtime.systemusinginstallers.IsisComponentProvider;
-
-public class IsisInjectModule {
-
-    @SuppressWarnings("unused") // dependency graph constraint
-    @Inject private IsisConfiguration isisConfiguration; 
-    
-    @Produces @ApplicationScoped
-    protected IsisSessionFactory provideIsisSessionFactory() {
-        
-        final IsisComponentProvider componentProvider = IsisComponentProvider
-                .builder()
-                .build();
-        
-        final IsisSessionFactoryBuilder builder =
-                new IsisSessionFactoryBuilder(componentProvider);
-        
-        // as a side-effect, if the metamodel turns out to be invalid, then
-        // this will push the MetaModelInvalidException into IsisContext.
-        IsisSessionFactory sessionFactory = builder.buildSessionFactory();
-        
-        return sessionFactory;
-    }
-    
-    public static class Nested {
-        
-        @Inject private IsisSessionFactory isisSessionFactory;
-    
-        @Produces @ApplicationScoped
-        protected ServicesInjector getServicesInjector() {
-            return isisSessionFactory.getServicesInjector();
-        }
-        
-        @Produces @ApplicationScoped
-        protected SpecificationLoader getSpecificationLoader() {
-            return isisSessionFactory.getSpecificationLoader();
-        }
-        
-    }
-    
-    
-    
-    
-    
-
-
-}
diff --git a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactory.java b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactory.java
index fc5ef2f..4d7178a 100644
--- a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactory.java
+++ b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactory.java
@@ -23,12 +23,18 @@ import java.util.List;
 import java.util.concurrent.Callable;
 import java.util.stream.Collectors;
 
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.ejb.Singleton;
+import javax.ejb.Startup;
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Produces;
 import javax.inject.Inject;
 
-import org.apache.isis.applib.annotation.Programmatic;
 import org.apache.isis.applib.services.i18n.TranslationService;
 import org.apache.isis.applib.services.title.TitleService;
 import org.apache.isis.commons.internal.base._Blackhole;
+import org.apache.isis.commons.internal.context._Context;
 import org.apache.isis.config.IsisConfiguration;
 import org.apache.isis.core.metamodel.services.ServicesInjector;
 import org.apache.isis.core.metamodel.spec.ObjectSpecification;
@@ -42,6 +48,7 @@ import org.apache.isis.core.runtime.system.persistence.PersistenceSession;
 import org.apache.isis.core.runtime.system.persistence.PersistenceSessionFactory;
 import org.apache.isis.core.runtime.system.transaction.IsisTransactionManager;
 import org.apache.isis.core.runtime.system.transaction.IsisTransactionManagerException;
+import org.apache.isis.core.runtime.systemusinginstallers.IsisComponentProvider;
 import org.apache.isis.core.security.authentication.AuthenticationSession;
 import org.apache.isis.core.security.authentication.manager.AuthenticationManager;
 import org.apache.isis.core.security.authorization.manager.AuthorizationManager;
@@ -60,36 +67,50 @@ import org.apache.isis.core.security.authorization.manager.AuthorizationManager;
  *     it can be {@link Inject}'d into other domain services.
  * </p>
  */
+@Singleton @ApplicationScoped @Startup
 public class IsisSessionFactory {
 
     //private final static Logger LOG = LoggerFactory.getLogger(IsisSessionFactory.class);
 
-    // -- constructor, fields, accessors
-
-    private final IsisConfiguration configuration;
-    private final SpecificationLoader specificationLoader;
-    private final ServicesInjector servicesInjector;
-    private final AuthenticationManager authenticationManager;
-    private final AuthorizationManager authorizationManager;
-    private final PersistenceSessionFactory persistenceSessionFactory;
+    @Inject private IsisConfiguration configuration;
+    
+    private ServicesInjector servicesInjector;
+    private SpecificationLoader specificationLoader;
+    private AuthenticationManager authenticationManager;
+    private AuthorizationManager authorizationManager;
+    private PersistenceSessionFactory persistenceSessionFactory;
+    private ServiceInitializer serviceInitializer;
 
-    IsisSessionFactory(final ServicesInjector servicesInjector) {
+    @PostConstruct
+    public void init() {
 
+        if(_Context.getIfAny(IsisSessionFactory.class)!=null) {
+            return;
+        }
+        
+        System.out.println("!!!!!!!!!!!!! IsisSessionFactory INIT " + hashCode());
+        
+        final IsisComponentProvider componentProvider = IsisComponentProvider
+                .builder()
+                .build();
+        
+        final IsisSessionFactoryBuilder builder =
+                new IsisSessionFactoryBuilder(componentProvider);
+        
+        // as a side-effect, if the metamodel turns out to be invalid, then
+        // this will push the MetaModelInvalidException into IsisContext.
+        IsisSessionFactory sessionFactory = builder.buildSessionFactory(()->this);
+    }
+    
+    void setServicesInjector(ServicesInjector servicesInjector) {
         this.servicesInjector = servicesInjector;
-
-        this.configuration = IsisContext.getConfiguration();
         this.specificationLoader = servicesInjector.getSpecificationLoader();
         this.authenticationManager = servicesInjector.getAuthenticationManager();
         this.authorizationManager = servicesInjector.getAuthorizationManager();
         this.persistenceSessionFactory = servicesInjector.lookupServiceElseFail(PersistenceSessionFactory.class);
     }
 
-    // -- constructServices, destroyServicesAndShutdown
-
-    private ServiceInitializer serviceInitializer;
-
-    @Programmatic
-    public void constructServices() {
+    void constructServices() {
 
         // do postConstruct.  We store the initializer to do preDestroy on shutdown
         serviceInitializer = new ServiceInitializer(configuration, servicesInjector.streamServices().collect(Collectors.toList()));
@@ -151,8 +172,7 @@ public class IsisSessionFactory {
         }
     }
 
-
-    @Programmatic
+    @PreDestroy
     public void destroyServicesAndShutdown() {
         destroyServices();
         shutdown();
@@ -202,7 +222,6 @@ public class IsisSessionFactory {
     /**
      * Creates and {@link IsisSession#open() open}s the {@link IsisSession}.
      */
-    @Programmatic
     public IsisSession openSession(final AuthenticationSession authenticationSession) {
 
         closeSession();
@@ -215,7 +234,6 @@ public class IsisSessionFactory {
         return session;
     }
 
-    @Programmatic
     public void closeSession() {
         final IsisSession existingSessionIfAny = getCurrentSession();
         if (existingSessionIfAny == null) {
@@ -225,7 +243,6 @@ public class IsisSessionFactory {
         currentSession.set(null);
     }
 
-    @Programmatic
     public IsisSession getCurrentSession() {
         return currentSession.get();
     }
@@ -235,12 +252,10 @@ public class IsisSessionFactory {
         return currentSession.getPersistenceSession().getTransactionManager();
     }
 
-    @Programmatic
     public boolean inSession() {
         return getCurrentSession() != null;
     }
 
-    @Programmatic
     public boolean inTransaction() {
         if (inSession()) {
             if (getCurrentSession().getCurrentTransaction() != null) {
@@ -256,7 +271,6 @@ public class IsisSessionFactory {
      * As per {@link #doInSession(Runnable, AuthenticationSession)}, using a default {@link InitialisationSession}.
      * @param runnable
      */
-    @Programmatic
     public void doInSession(final Runnable runnable) {
         doInSession(runnable, new InitialisationSession());
     }
@@ -269,7 +283,6 @@ public class IsisSessionFactory {
      * @param runnable The piece of code to run.
      * @param authenticationSession
      */
-    @Programmatic
     public void doInSession(final Runnable runnable, final AuthenticationSession authenticationSession) {
         doInSession(new Callable<Void>() {
             @Override
@@ -283,7 +296,6 @@ public class IsisSessionFactory {
     /**
      * As per {@link #doInSession(Callable), AuthenticationSession}, using a default {@link InitialisationSession}.
      */
-    @Programmatic
     public <R> R doInSession(final Callable<R> callable) {
         return doInSession(callable, new InitialisationSession());
     }
@@ -296,7 +308,6 @@ public class IsisSessionFactory {
      * @param callable The piece of code to run.
      * @param authenticationSession - the user to run under
      */
-    @Programmatic
     public <R> R doInSession(final Callable<R> callable, final AuthenticationSession authenticationSession) {
         final IsisSessionFactory sessionFactory = this;
         boolean noSession = !sessionFactory.inSession();
@@ -317,14 +328,12 @@ public class IsisSessionFactory {
         }
     }
 
-
-
     // -- component accessors
 
     /**
      * The {@link ApplicationScopedComponent application-scoped} {@link ServicesInjector}.
      */
-    @Programmatic
+    @Produces @ApplicationScoped
     public ServicesInjector getServicesInjector() {
         return servicesInjector;
     }
@@ -333,7 +342,7 @@ public class IsisSessionFactory {
      * The {@link ApplicationScopedComponent application-scoped}
      * {@link SpecificationLoader}.
      */
-    @Programmatic
+    @Produces @ApplicationScoped
     public SpecificationLoader getSpecificationLoader() {
         return specificationLoader;
     }
@@ -344,7 +353,6 @@ public class IsisSessionFactory {
      * {@link IsisSession#getAuthenticationSession() within} the
      * {@link IsisSession}.
      */
-    @Programmatic
     public AuthenticationManager getAuthenticationManager() {
         return authenticationManager;
     }
@@ -353,7 +361,6 @@ public class IsisSessionFactory {
      * The {@link AuthorizationManager} that will be used to authorize access to
      * domain objects.
      */
-    @Programmatic
     public AuthorizationManager getAuthorizationManager() {
         return authorizationManager;
     }
@@ -363,12 +370,9 @@ public class IsisSessionFactory {
      * {@link PersistenceSession} {@link IsisSession#getPersistenceSession()
      * within} the {@link IsisSession}.
      */
-    @Programmatic
     public PersistenceSessionFactory getPersistenceSessionFactory() {
         return persistenceSessionFactory;
     }
 
 
-
-
 }
diff --git a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactoryBuilder.java b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactoryBuilder.java
index e161dc4..a63f339 100644
--- a/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactoryBuilder.java
+++ b/core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactoryBuilder.java
@@ -25,6 +25,7 @@ import java.util.Collection;
 import java.util.List;
 import java.util.concurrent.Callable;
 import java.util.concurrent.Future;
+import java.util.function.Supplier;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -62,8 +63,6 @@ public class IsisSessionFactoryBuilder {
 
     public static final Logger LOG = LoggerFactory.getLogger(IsisSessionFactoryBuilder.class);
 
-    private boolean initialized = false;
-
     // -- constructors, accessors
 
     private final IsisComponentProvider componentProvider;
@@ -78,13 +77,7 @@ public class IsisSessionFactoryBuilder {
 
     // -- buildSessionFactory
 
-    public IsisSessionFactory buildSessionFactory() {
-
-        if (initialized) {
-            throw new IllegalStateException("Already initialized");
-        }
-        initialized = true;
-
+    public IsisSessionFactory buildSessionFactory(Supplier<IsisSessionFactory> sfInstanceSupplier) {
 
         LOG.info("initialising Isis System");
         LOG.info("working directory: {}", new File(".").getAbsolutePath());
@@ -139,17 +132,16 @@ public class IsisSessionFactoryBuilder {
 
             servicesInjector.validateServices();
 
-            // instantiate the IsisSessionFactory
-            isisSessionFactory = new IsisSessionFactory(servicesInjector);
+            // instantiate or reuse the IsisSessionFactory
+            isisSessionFactory = sfInstanceSupplier.get();
+            isisSessionFactory.setServicesInjector(servicesInjector);
 
             // now, add the IsisSessionFactory itself into ServicesInjector, so it can be @javax.inject.Inject'd
             // into any internal domain services
-            servicesInjector.addFallbackIfRequired(IsisSessionFactory.class, isisSessionFactory);
-
-
+//            servicesInjector.addFallbackIfRequired(IsisSessionFactory.class, isisSessionFactory);
 
             // finally, wire up components and components into services...
-            servicesInjector.autowire();
+//            servicesInjector.autowire();
 
             // ... and make IsisSessionFactory available via the IsisContext static for those places where we cannot
             // yet inject.
diff --git a/core/runtime/src/main/java/org/apache/isis/core/webapp/IsisWebAppContextListener.java b/core/runtime/src/main/java/org/apache/isis/core/webapp/IsisWebAppContextListener.java
index 55f466d..063f722 100644
--- a/core/runtime/src/main/java/org/apache/isis/core/webapp/IsisWebAppContextListener.java
+++ b/core/runtime/src/main/java/org/apache/isis/core/webapp/IsisWebAppContextListener.java
@@ -30,11 +30,12 @@ import javax.servlet.ServletException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import org.apache.isis.commons.internal.base._Blackhole;
 import org.apache.isis.commons.internal.context._Context;
 import org.apache.isis.config.AppConfigLocator;
 import org.apache.isis.config.IsisConfiguration;
-import org.apache.isis.config.NotFoundPolicy;
 import org.apache.isis.config.IsisConfiguration.ContainsPolicy;
+import org.apache.isis.config.NotFoundPolicy;
 import org.apache.isis.config.builder.IsisConfigurationBuilder;
 import org.apache.isis.core.runtime.system.context.IsisContext;
 import org.apache.isis.core.webapp.modules.WebModule;
@@ -71,22 +72,24 @@ public class IsisWebAppContextListener implements ServletContextListener {
 
         final ServletContext servletContext = event.getServletContext();
         
-        LOG.info("=== PHASE 1 === Setting up ServletContext parameters");
-  
-        //[ahuber] set the ServletContext initializing thread as preliminary default until overridden by
+        // set the ServletContext initializing thread as preliminary default until overridden by
         // IsisWicketApplication#init() or others that better know what ClassLoader to use as application default.
         _Context.setDefaultClassLoader(Thread.currentThread().getContextClassLoader(), false);
-        
         _Context.putSingleton(ServletContext.class, servletContext);
-        
         putContextPathIfPresent(servletContext.getContextPath());
         
-        @SuppressWarnings("unused") // finalize the config (build and regard immutable)
+        LOG.info("=== PHASE 1 === Setting up IoC from AppManifest");
+        
+        // finalize the config (build and regard immutable)
+        // as a side-effect bootstrap CDI, if the environment we are running on does not have its own 
         IsisConfiguration isisConfiguration = AppConfigLocator.getAppConfig().isisConfiguration();
+        _Blackhole.consume(isisConfiguration);
         
-        //[2039] environment priming no longer suppoerted
+        LOG.info("=== PHASE 2 === Setting up ServletContext");
+        
+        //[2039] environment priming no longer supported
         //_Config.acceptBuilder(IsisContext.EnvironmentPrimer::primeEnvironment);
-
+        
         final WebModuleContext webModuleContext = new WebModuleContext(servletContext);
         
         final List<WebModule> webModules =
@@ -94,7 +97,7 @@ public class IsisWebAppContextListener implements ServletContextListener {
                  .peek(module->module.prepare(webModuleContext)) // prepare context
                  .collect(Collectors.toList());
 
-        LOG.info("=== PHASE 2 === Initializing the ServletContext");
+        LOG.info("=== PHASE 3 === Initializing the ServletContext");
         
         webModules.stream()
         .filter(module->module.isApplicable(webModuleContext)) // filter those WebModules that are applicable
@@ -116,6 +119,8 @@ public class IsisWebAppContextListener implements ServletContextListener {
     public void contextDestroyed(ServletContextEvent event) {
         activeListeners.forEach(listener->shutdownListener(event, listener));
         activeListeners.clear();
+        
+        _Context.clear();
     }
     
     // -- HELPER
diff --git a/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java b/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java
index 6c55f2f..92bb599 100644
--- a/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java
+++ b/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java
@@ -77,14 +77,12 @@ import org.apache.isis.core.commons.ensure.Ensure;
 import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
 import org.apache.isis.core.metamodel.specloader.validator.MetaModelInvalidException;
 import org.apache.isis.core.runtime.system.context.IsisContext;
-import org.apache.isis.core.runtime.system.session.IsisInjectModule;
 import org.apache.isis.core.runtime.system.session.IsisSessionFactory;
 import org.apache.isis.core.runtime.threadpool.ThreadPoolSupport;
 import org.apache.isis.core.security.authentication.AuthenticationSession;
 import org.apache.isis.viewer.wicket.model.isis.WicketViewerSettings;
 import org.apache.isis.viewer.wicket.model.isis.WicketViewerSettingsAccessor;
 import org.apache.isis.viewer.wicket.model.mementos.ObjectAdapterMemento;
-import org.apache.isis.viewer.wicket.model.models.ImageResourceCache;
 import org.apache.isis.viewer.wicket.model.models.PageType;
 import org.apache.isis.viewer.wicket.ui.ComponentFactory;
 import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistry;
@@ -177,8 +175,8 @@ implements ComponentFactoryRegistryAccessor, PageClassRegistryAccessor, WicketVi
     }
 
     @Inject private ComponentFactoryRegistry componentFactoryRegistry;
-    @Inject private ImageResourceCache imageCache;
-    @Inject private WicketViewerSettings wicketViewerSettings;
+//    @Inject private ImageResourceCache imageCache;
+//    @Inject private WicketViewerSettings wicketViewerSettings;
     @Inject private PageClassRegistry pageClassRegistry;
     @Inject private IsisSessionFactory isisSessionFactory;
     @Inject private WicketViewerSettings settings;
@@ -251,7 +249,7 @@ implements ComponentFactoryRegistryAccessor, PageClassRegistryAccessor, WicketVi
             requestCycleListeners.add(new PageRequestHandlerTracker());
             
             // configure wicket/cdi
-            BeanManager beanManager = _CDI.cdi().get().getBeanManager();
+            BeanManager beanManager = _CDI.getBeanManager();
             new CdiConfiguration(beanManager).configure(this);
 
 
@@ -653,19 +651,6 @@ implements ComponentFactoryRegistryAccessor, PageClassRegistryAccessor, WicketVi
                         : RuntimeConfigurationType.DEPLOYMENT;
     }
     
-    // //////////////////////////////////////
-
-    protected IsisInjectModule newIsisModule() {
-        return new IsisInjectModule();
-    }
-
-    // //////////////////////////////////////
-
-
-    protected void initWicketComponentInjection(/*final Injector injector*/) {
-        //FIXME getComponentInstantiationListeners().add(new GuiceComponentInjector(this, injector, false));
-    }
-
     // /////////////////////////////////////////////////
     // Wicket Hooks
     // /////////////////////////////////////////////////
diff --git a/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/wicket/WebRequestCycleForIsis.java b/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/wicket/WebRequestCycleForIsis.java
index f5be6cb..79449fd 100644
--- a/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/wicket/WebRequestCycleForIsis.java
+++ b/core/viewer-wicket-impl/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/wicket/WebRequestCycleForIsis.java
@@ -82,7 +82,7 @@ public class WebRequestCycleForIsis implements IRequestCycleListener {
     private static final Logger LOG = LoggerFactory.getLogger(WebRequestCycleForIsis.class);
 
     private PageClassRegistry pageClassRegistry;
-
+    
     @Override
     public synchronized void onBeginRequest(RequestCycle requestCycle) {
 
@@ -353,6 +353,9 @@ public class WebRequestCycleForIsis implements IRequestCycleListener {
     }
 
     // -- Dependencies (from isis' context)
+    
+    
+    
     protected ServicesInjector getServicesInjector() {
         return getIsisSessionFactory().getServicesInjector();
     }
diff --git a/core/viewer-wicket-impl/src/test/java/org/apache/isis/viewer/wicket/viewer/isisWicketModule_bindingsStandard_Test.java b/core/viewer-wicket-impl/src/test/java/org/apache/isis/viewer/wicket/viewer/isisWicketModule_bindingsStandard_Test.java
deleted file mode 100644
index b51a552..0000000
--- a/core/viewer-wicket-impl/src/test/java/org/apache/isis/viewer/wicket/viewer/isisWicketModule_bindingsStandard_Test.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.isis.viewer.wicket.viewer;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-@RunWith(Parameterized.class)
-public class isisWicketModule_bindingsStandard_Test {
-
-//FIXME    
-//    @Rule
-//    public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);
-//
-//    @Mock
-//    private ServletContext mockServletContext;
-//
-//    private IsisWicketModule isisWicketModule;
-//	private Injector injector;
-//	private final Class<?> from;
-//	private final Class<?> to;
-//
-//
-//	@Parameters
-//	public static Collection<Object[]> params() {
-//		return Arrays.asList(new Object[][] { 
-//			{ ComponentFactoryRegistrar.class, ComponentFactoryRegistrarDefault.class }, 
-//			{ ComponentFactoryRegistry.class, ComponentFactoryRegistryDefault.class }, 
-//			{ PageClassList.class, PageClassListDefault.class },
-//			{ PageClassRegistry.class, PageClassRegistryDefault.class }, 
-//		});
-//	}
-//
-//	public isisWicketModule_bindingsStandard_Test(final Class<?> from, final Class<?> to) {
-//		this.from = from;
-//		this.to = to;
-//	}
-//
-//	@Before
-//	public void setUp() throws Exception {
-//	    
-//	    _Config.clear();
-//		        
-//        isisWicketModule = new IsisWicketModule(mockServletContext);
-//
-//        context.checking(new Expectations() {{
-//            allowing(mockServletContext);
-//        }});
-//
-//		injector = Guice.createInjector(isisWicketModule, new ConfigModule());
-//	}
-//
-//	@Test
-//	public void binding() {
-//		final Object instance = injector.getInstance(from);
-//		assertThat(instance, is(instanceOf(to)));
-//	}
-//
-//	// -- CONFIGURATION BINDING
-//
-//	private static class ConfigModule extends AbstractModule {
-//
-//        @Override 
-//		protected void configure() {
-//			bind(IsisConfiguration.class).toProvider(new Provider<IsisConfiguration>() {
-//                @Override
-//                public IsisConfiguration get() {
-//                    return _Config.getConfiguration();
-//                }
-//            });
-//		}
-//	}
-
-}