You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polygene.apache.org by ni...@apache.org on 2015/12/16 07:17:38 UTC

[1/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Repository: zest-java
Updated Branches:
  refs/heads/ZEST-132 6138c3057 -> a5be013f3


http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/registration/RegisterHandlingEventTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/registration/RegisterHandlingEventTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/registration/RegisterHandlingEventTest.java
index 8482f0f..eb6e2db 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/registration/RegisterHandlingEventTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/registration/RegisterHandlingEventTest.java
@@ -60,7 +60,7 @@ public class RegisterHandlingEventTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 
@@ -129,11 +129,11 @@ public class RegisterHandlingEventTest extends TestApplication
         throws Exception
     {
         deviation_3c_VoyageNumber_Unknown();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
 
         // Receive 1st time (store event so that it turns up in query)
         uow.complete();
-        tempUow = module.newUnitOfWork();
+        tempUow = uowf.newUnitOfWork();
         handlingEvent = HANDLING_EVENTS.createHandlingEvent( DAY1, DAY1, trackingId, RECEIVE, HONGKONG, noVoyage );
         tempUow.complete();
 
@@ -148,11 +148,11 @@ public class RegisterHandlingEventTest extends TestApplication
         throws Exception
     {
         deviation_4a_DuplicateEvent_Receive();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
 
         uow.complete();
         // In customs 1st time
-        tempUow = module.newUnitOfWork();
+        tempUow = uowf.newUnitOfWork();
         handlingEvent = HANDLING_EVENTS.createHandlingEvent( DAY1, DAY1, trackingId, CUSTOMS, HONGKONG, noVoyage );
         tempUow.complete();
 
@@ -167,11 +167,11 @@ public class RegisterHandlingEventTest extends TestApplication
         throws Exception
     {
         deviation_4a_DuplicateEvent_Customs();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
 
         uow.complete();
         // Claimed 1st time
-        tempUow = module.newUnitOfWork();
+        tempUow = uowf.newUnitOfWork();
         handlingEvent = HANDLING_EVENTS.createHandlingEvent( DAY1, DAY1, trackingId, CLAIM, HONGKONG, noVoyage );
         tempUow.complete();
 
@@ -200,8 +200,8 @@ public class RegisterHandlingEventTest extends TestApplication
         deviation_5a_NoHandlingAfterClaim();
 
         // Delete handling events from memory
-        tempUow = module.newUnitOfWork();
-        Query<HandlingEventEntity> events = tempUow.newQuery( module.newQueryBuilder( HandlingEventEntity.class ) );
+        tempUow = uowf.newUnitOfWork();
+        Query<HandlingEventEntity> events = tempUow.newQuery( qbf.newQueryBuilder( HandlingEventEntity.class ) );
         for( HandlingEvent event : events )
         {
             tempUow.remove( event );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest.java
----------------------------------------------------------------------
diff --git a/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest.java b/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest.java
index 76c82e9..78f470b 100644
--- a/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest.java
+++ b/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest.java
@@ -14,6 +14,8 @@
 
 package org.apache.zest.dci.moneytransfer.test;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.BeforeClass;
@@ -45,6 +47,7 @@ public class TransferMoneyTest
     public static final String CHECKING_ACCOUNT_ID = "CheckingAccountId";
     public static final String CREDITOR_ID1 = "BakerAccount";
     public static final String CREDITOR_ID2 = "ButcherAccount";
+    private static UnitOfWorkFactory uowf;
 
     @BeforeClass
     public static void setup()
@@ -55,6 +58,7 @@ public class TransferMoneyTest
             public void assemble( ModuleAssembly module )
                 throws AssemblyException
             {
+                module.withDefaultUnitOfWorkFactory();
                 module.entities(
                     CheckingAccountRolemap.class,
                     SavingsAccountRolemap.class,
@@ -63,7 +67,7 @@ public class TransferMoneyTest
                 new EntityTestAssembler().assemble( module );
             }
         };
-
+        uowf = assembler.module().unitOfWorkFactory();
         bootstrapData( assembler );
     }
 
@@ -85,7 +89,7 @@ public class TransferMoneyTest
 
     public void printBalances()
     {
-        UnitOfWork uow = assembler.module().newUnitOfWork( UsecaseBuilder.newUsecase( "Print balances" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Print balances" ) );
 
         try
         {
@@ -105,7 +109,7 @@ public class TransferMoneyTest
     private static void bootstrapData( SingletonAssembler assembler )
         throws Exception
     {
-        UnitOfWork uow = assembler.module().newUnitOfWork( newUsecase( "Bootstrap data" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Bootstrap data" ) );
         try
         {
             SavingsAccountEntity savingsAccount = uow.newEntity( SavingsAccountEntity.class, SAVINGS_ACCOUNT_ID );
@@ -134,8 +138,7 @@ public class TransferMoneyTest
     public void transferHalfOfMoneyFromSavingsToChecking()
         throws Exception
     {
-        UnitOfWork uow = assembler.module()
-            .newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
 
         try
         {
@@ -163,8 +166,7 @@ public class TransferMoneyTest
     public void transferTwiceOfMoneyFromSavingsToChecking()
         throws Exception
     {
-        UnitOfWork uow = assembler.module()
-            .newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
 
         try
         {
@@ -192,7 +194,7 @@ public class TransferMoneyTest
     public void payAllBills()
         throws Exception
     {
-        UnitOfWork uow = assembler.module().newUnitOfWork( newUsecase( "Pay all bills from checking to creditors" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Pay all bills from checking to creditors" ) );
         try
         {
             BalanceData source = uow.get( BalanceData.class, CHECKING_ACCOUNT_ID );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest2.java
----------------------------------------------------------------------
diff --git a/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest2.java b/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest2.java
index 8507b8b..7d4a11c 100644
--- a/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest2.java
+++ b/samples/dci/src/test/java/org/apache/zest/dci/moneytransfer/test/TransferMoneyTest2.java
@@ -14,6 +14,8 @@
 
 package org.apache.zest.dci.moneytransfer.test;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.BeforeClass;
@@ -44,6 +46,7 @@ public class TransferMoneyTest2
     public static final String CHECKING_ACCOUNT_ID = "CheckingAccountId";
     public static final String CREDITOR_ID1 = "BakerAccount";
     public static final String CREDITOR_ID2 = "ButcherAccount";
+    private static UnitOfWorkFactory uowf;
 
     @BeforeClass
     public static void setup()
@@ -54,6 +57,7 @@ public class TransferMoneyTest2
             public void assemble( ModuleAssembly module )
                 throws AssemblyException
             {
+                module.withDefaultUnitOfWorkFactory();
                 module.entities(
                     CheckingAccountEntity.class,
                     SavingsAccountEntity.class,
@@ -67,7 +71,7 @@ public class TransferMoneyTest2
         };
 
         module = assembler.module();
-
+        uowf = module.unitOfWorkFactory();
         bootstrapData();
     }
 
@@ -89,7 +93,7 @@ public class TransferMoneyTest2
 
     private void printBalances()
     {
-        UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Print balances" ) );
+        UnitOfWork uow = module.unitOfWorkFactory().newUnitOfWork( UsecaseBuilder.newUsecase( "Print balances" ) );
 
         try
         {
@@ -109,7 +113,7 @@ public class TransferMoneyTest2
     private static void bootstrapData()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork( newUsecase( "Bootstrap data" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Bootstrap data" ) );
         try
         {
             SavingsAccountEntity account = uow.newEntity( SavingsAccountEntity.class, SAVINGS_ACCOUNT_ID );
@@ -138,7 +142,7 @@ public class TransferMoneyTest2
     public void transferHalfOfMoneyFromSavingsToChecking()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
 
         try
         {
@@ -166,7 +170,7 @@ public class TransferMoneyTest2
     public void transferTwiceOfMoneyFromSavingsToChecking()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Transfer from savings to checking" ) );
 
         try
         {
@@ -194,7 +198,7 @@ public class TransferMoneyTest2
     public void payAllBills()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork( newUsecase( "Pay all bills from checking to creditors" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Pay all bills from checking to creditors" ) );
         try
         {
             BalanceData source = uow.get( BalanceData.class, CHECKING_ACCOUNT_ID );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/context/EventsService.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/EventsService.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/EventsService.java
index e232e59..d120cc5 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/EventsService.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/EventsService.java
@@ -25,11 +25,12 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceComposite;
 import org.apache.zest.api.structure.Application;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCallback;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.functional.Iterables;
 import org.apache.zest.library.rest.server.api.ObjectSelection;
 import org.apache.zest.sample.forum.domainevent.DomainEventValue;
@@ -47,7 +48,11 @@ public interface EventsService
         implements InvocationHandler
     {
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
+
+        @Structure
+        ValueBuilderFactory vbf;
+
         @Structure
         Application application;
 
@@ -55,9 +60,9 @@ public interface EventsService
         public Object invoke( Object proxy, Method method, Object[] args )
             throws Throwable
         {
-            UnitOfWork unitOfWork = module.currentUnitOfWork();
+            UnitOfWork unitOfWork = uowf.currentUnitOfWork();
 
-            ValueBuilder<DomainEventValue> builder = module.newValueBuilder( DomainEventValue.class );
+            ValueBuilder<DomainEventValue> builder = vbf.newValueBuilder( DomainEventValue.class );
             DomainEventValue prototype = builder.prototype();
             prototype.version().set( application.version() );
             prototype.timestamp().set( unitOfWork.currentTime() );
@@ -69,7 +74,7 @@ public interface EventsService
             {
                 idx++;
                 String name = "param" + idx;
-                ValueBuilder<ParameterValue> parameterBuilder = module.newValueBuilder( ParameterValue.class );
+                ValueBuilder<ParameterValue> parameterBuilder = vbf.newValueBuilder( ParameterValue.class );
                 parameterBuilder.prototype().name().set( name );
                 parameterBuilder.prototype().value().set( arg );
                 prototype.parameters().get().add( parameterBuilder.newInstance() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumAdministration.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumAdministration.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumAdministration.java
index f4f61f7..8280726 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumAdministration.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumAdministration.java
@@ -22,7 +22,9 @@ import org.apache.zest.api.constraint.Name;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
 import org.apache.zest.api.query.Query;
+import org.apache.zest.api.query.QueryBuilderFactory;
 import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.rest.server.api.ResourceIndex;
 import org.apache.zest.library.rest.server.api.dci.Role;
 import org.apache.zest.sample.forum.data.entity.Board;
@@ -36,7 +38,10 @@ public class ForumAdministration
     implements ResourceIndex<Query<Board>>
 {
     @Structure
-    Module module;
+    UnitOfWorkFactory uowf;
+
+    @Structure
+    QueryBuilderFactory qbf;
 
     ForumAdmin forumAdmin = new ForumAdmin();
     Administrator administrator = new Administrator();
@@ -61,17 +66,15 @@ public class ForumAdministration
     protected class ForumAdmin
         extends Role<Forum>
     {
-        @Structure
-        Module module;
 
         public Query<Board> boards()
         {
-            return module.newQueryBuilder( Board.class ).newQuery( self.boards() );
+            return qbf.newQueryBuilder( Board.class ).newQuery( self.boards() );
         }
 
         public Board createBoard( String name )
         {
-            Board board = module.currentUnitOfWork().newEntity( Board.class );
+            Board board = uowf.currentUnitOfWork().newEntity( Board.class );
             board.name().set( name );
             administrator.makeModerator( board );
             return board;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumsAdministration.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumsAdministration.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumsAdministration.java
index 7ed4e4e..64654b9 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumsAdministration.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/administration/ForumsAdministration.java
@@ -22,7 +22,7 @@ import org.apache.zest.api.constraint.Name;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
 import org.apache.zest.api.query.Query;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.rest.server.api.ResourceIndex;
 import org.apache.zest.library.rest.server.api.dci.Role;
 import org.apache.zest.sample.forum.data.entity.Forum;
@@ -36,7 +36,7 @@ public class ForumsAdministration
     implements ResourceIndex<Query<Forum>>
 {
     @Structure
-    Module module;
+    UnitOfWorkFactory uowf;
 
     ForumsAdmin forumsAdmin = new ForumsAdmin();
     Administrator administrator = new Administrator();
@@ -68,7 +68,7 @@ public class ForumsAdministration
 
         public Forum createForum( String name )
         {
-            Forum forum = module.currentUnitOfWork().newEntity( Forum.class );
+            Forum forum = uowf.currentUnitOfWork().newEntity( Forum.class );
             forum.name().set( name );
             administrator.makeModerator( forum );
             return forum;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/context/login/Login.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/login/Login.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/login/Login.java
index bac5019..d18005f 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/login/Login.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/login/Login.java
@@ -20,23 +20,33 @@ package org.apache.zest.sample.forum.context.login;
 
 import org.apache.zest.api.constraint.Name;
 import org.apache.zest.api.injection.scope.Structure;
+import org.apache.zest.api.query.QueryBuilder;
+import org.apache.zest.api.query.QueryBuilderFactory;
 import org.apache.zest.api.query.QueryExpressions;
 import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.sample.forum.data.entity.User;
 
+import static org.apache.zest.api.query.QueryExpressions.*;
+
 /**
  * TODO
  */
 public class Login
 {
     @Structure
-    Module module;
+    UnitOfWorkFactory uowf;
+
+    @Structure
+    QueryBuilderFactory qbf;
 
     public void login( @Name( "name" ) String name, @Name( "password" ) String password )
     {
-        User user = module.currentUnitOfWork()
-            .newQuery( module.newQueryBuilder( User.class )
-                           .where( QueryExpressions.eq( QueryExpressions.templateFor( User.class ).name(), name ) ) )
+        QueryBuilder<User> builder = qbf.newQueryBuilder( User.class )
+            .where( eq( templateFor( User.class ).name(), name ) );
+
+        User user = uowf.currentUnitOfWork()
+            .newQuery( builder )
             .find();
 
         if( user == null || !user.isCorrectPassword( password ) )

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewBoard.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewBoard.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewBoard.java
index 563f6b0..3730b11 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewBoard.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewBoard.java
@@ -20,14 +20,14 @@ package org.apache.zest.sample.forum.context.view;
 
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.rest.server.api.ResourceIndex;
 import org.apache.zest.library.rest.server.api.dci.Role;
 import org.apache.zest.sample.forum.data.Moderators;
 import org.apache.zest.sample.forum.data.entity.Board;
-import org.apache.zest.sample.forum.data.entity.Topic;
 import org.apache.zest.sample.forum.data.entity.Forum;
 import org.apache.zest.sample.forum.data.entity.Post;
+import org.apache.zest.sample.forum.data.entity.Topic;
 import org.apache.zest.sample.forum.data.entity.User;
 
 import static org.apache.zest.api.property.Numbers.add;
@@ -94,15 +94,15 @@ public class ViewBoard
         extends Role<Board>
     {
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
 
         Topic createTopic( String subject, String message, BoardViewer poster )
         {
-            Topic topic = module.currentUnitOfWork().newEntity( Topic.class );
+            Topic topic = uowf.currentUnitOfWork().newEntity( Topic.class );
 
             topic.subject().set( subject );
 
-            Post post = module.currentUnitOfWork().newEntity( Post.class );
+            Post post = uowf.currentUnitOfWork().newEntity( Post.class );
             post.message().set( message );
 
             // Moderation checks

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewPost.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewPost.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewPost.java
index 09adc3c..7df3a0e 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewPost.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/context/view/ViewPost.java
@@ -22,7 +22,7 @@ import java.util.Date;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
 import org.apache.zest.api.property.Numbers;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.rest.server.api.ResourceIndex;
 import org.apache.zest.library.rest.server.api.dci.Role;
 import org.apache.zest.sample.forum.data.entity.Post;
@@ -62,14 +62,14 @@ public class ViewPost
         extends Role<Topic>
     {
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
 
         public Post reply( String message, PostView viewPost )
         {
-            Post post = module.currentUnitOfWork().newEntity( Post.class );
+            Post post = uowf.currentUnitOfWork().newEntity( Post.class );
             post.message().set( message );
             post.createdBy().set( poster.self() );
-            post.createdOn().set( new Date( module.currentUnitOfWork().currentTime() ) );
+            post.createdOn().set( new Date( uowf.currentUnitOfWork().currentTime() ) );
             post.replyTo().set( viewPost.self() );
 
             self().lastPost().set( post );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Forums.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Forums.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Forums.java
index 6c5e785..fe446f8 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Forums.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Forums.java
@@ -22,7 +22,8 @@ import org.apache.zest.api.entity.EntityComposite;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.query.Query;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.query.QueryBuilderFactory;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.sample.forum.data.Administrators;
 
 import static org.apache.zest.api.query.QueryExpressions.templateFor;
@@ -42,12 +43,15 @@ public interface Forums
         implements Forums
     {
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
+
+        @Structure
+        QueryBuilderFactory qbf;
 
         public Query<Forum> forums()
         {
-            return module.currentUnitOfWork()
-                .newQuery( module.newQueryBuilder( Forum.class ) )
+            return uowf.currentUnitOfWork()
+                .newQuery( qbf.newQueryBuilder( Forum.class ) )
                 .orderBy( templateFor( Forum.class ).name() );
         }
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Users.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Users.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Users.java
index b41f56f..0f18cfe 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Users.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/data/entity/Users.java
@@ -23,7 +23,8 @@ import org.apache.zest.api.entity.EntityComposite;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.query.Query;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.query.QueryBuilderFactory;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.sample.forum.context.Events;
 import org.apache.zest.sample.forum.context.signup.Registration;
 
@@ -47,28 +48,31 @@ public interface Users
         implements Users
     {
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
+
+        @Structure
+        QueryBuilderFactory qbf;
 
         @Override
         public Query<User> users()
         {
-            return module.currentUnitOfWork()
-                .newQuery( module.newQueryBuilder( User.class ) )
+            return uowf.currentUnitOfWork()
+                .newQuery( qbf.newQueryBuilder( User.class ) )
                 .orderBy( templateFor( User.class ).realName() );
         }
 
         @Override
         public User userNamed( String name )
         {
-            return module.currentUnitOfWork().newQuery(
-                module.newQueryBuilder( User.class ).where( eq( templateFor( User.class ).name(), name ) )
+            return uowf.currentUnitOfWork().newQuery(
+                qbf.newQueryBuilder( User.class ).where( eq( templateFor( User.class ).name(), name ) )
             ).find();
         }
 
         @Override
         public void signedup( Registration registration )
         {
-            EntityBuilder<User> builder = module.currentUnitOfWork().newEntityBuilder( User.class );
+            EntityBuilder<User> builder = uowf.currentUnitOfWork().newEntityBuilder( User.class );
             builder.instance().name().set( registration.name().get() );
             builder.instance().realName().set( registration.realName().get() );
             builder.instance().email().set( registration.email().get() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/domainevent/DomainEvent.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/domainevent/DomainEvent.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/domainevent/DomainEvent.java
index ed347f2..6cbec1a 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/domainevent/DomainEvent.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/domainevent/DomainEvent.java
@@ -26,11 +26,12 @@ import org.apache.zest.api.concern.Concerns;
 import org.apache.zest.api.concern.GenericConcern;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.structure.Application;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCallback;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.functional.Iterables;
 import org.apache.zest.library.rest.server.api.ObjectSelection;
 import org.restlet.Request;
@@ -46,7 +47,10 @@ public @interface DomainEvent
         extends GenericConcern
     {
         @Structure
-        Module module;
+        ValueBuilderFactory vbf;
+
+        @Structure
+        UnitOfWorkFactory uowf;
 
         @Structure
         Application application;
@@ -57,9 +61,9 @@ public @interface DomainEvent
         {
             Object result = next.invoke( proxy, method, args );
 
-            UnitOfWork unitOfWork = module.currentUnitOfWork();
+            UnitOfWork unitOfWork = uowf.currentUnitOfWork();
 
-            ValueBuilder<DomainEventValue> builder = module.newValueBuilder( DomainEventValue.class );
+            ValueBuilder<DomainEventValue> builder = vbf.newValueBuilder( DomainEventValue.class );
             DomainEventValue prototype = builder.prototype();
             prototype.version().set( application.version() );
             prototype.timestamp().set( unitOfWork.currentTime() );
@@ -71,7 +75,7 @@ public @interface DomainEvent
             {
                 idx++;
                 String name = "param" + idx;
-                ValueBuilder<ParameterValue> parameterBuilder = module.newValueBuilder( ParameterValue.class );
+                ValueBuilder<ParameterValue> parameterBuilder = vbf.newValueBuilder( ParameterValue.class );
                 parameterBuilder.prototype().name().set( name );
                 parameterBuilder.prototype().value().set( arg );
                 prototype.parameters().get().add( parameterBuilder.newInstance() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/rest/ForumRestlet.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/rest/ForumRestlet.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/rest/ForumRestlet.java
index c63077d..edf6fb1 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/rest/ForumRestlet.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/rest/ForumRestlet.java
@@ -33,6 +33,6 @@ public class ForumRestlet
     @Override
     protected Uniform createRoot( Request request, Response response )
     {
-        return module.newObject( RootResource.class, this );
+        return objectFactory.newObject( RootResource.class, this );
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/forum/src/main/java/org/apache/zest/sample/forum/service/BootstrapData.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/zest/sample/forum/service/BootstrapData.java b/samples/forum/src/main/java/org/apache/zest/sample/forum/service/BootstrapData.java
index c220d91..c635717 100644
--- a/samples/forum/src/main/java/org/apache/zest/sample/forum/service/BootstrapData.java
+++ b/samples/forum/src/main/java/org/apache/zest/sample/forum/service/BootstrapData.java
@@ -25,10 +25,10 @@ import org.apache.zest.api.mixin.InitializationException;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceComposite;
 import org.apache.zest.api.service.ServiceReference;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.sample.forum.data.entity.Forums;
 import org.apache.zest.sample.forum.data.entity.Users;
 
@@ -40,28 +40,27 @@ import org.apache.zest.sample.forum.data.entity.Users;
 public interface BootstrapData
     extends ServiceComposite
 {
-    
+
     void insertInitialData()
-            throws Exception;
+        throws Exception;
 
     class Activator
-            extends ActivatorAdapter<ServiceReference<BootstrapData>>
+        extends ActivatorAdapter<ServiceReference<BootstrapData>>
     {
 
         @Override
         public void afterActivation( ServiceReference<BootstrapData> activated )
-                throws Exception
+            throws Exception
         {
             activated.get().insertInitialData();
         }
-
     }
-    
+
     abstract class Mixin
         implements BootstrapData
     {
         @Structure
-        Module module;
+        private UnitOfWorkFactory module;
 
         @Override
         public void insertInitialData()
@@ -96,6 +95,5 @@ public interface BootstrapData
                 throw new InitializationException( e );
             }
         }
-
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/sql-support/src/main/java/org/apache/zest/sample/sqlsupport/Main.java
----------------------------------------------------------------------
diff --git a/samples/sql-support/src/main/java/org/apache/zest/sample/sqlsupport/Main.java b/samples/sql-support/src/main/java/org/apache/zest/sample/sqlsupport/Main.java
index ddb2d3e..4592e17 100644
--- a/samples/sql-support/src/main/java/org/apache/zest/sample/sqlsupport/Main.java
+++ b/samples/sql-support/src/main/java/org/apache/zest/sample/sqlsupport/Main.java
@@ -72,14 +72,14 @@ public class Main
 
         try {
 
-            UnitOfWork uow = domainModule.newUnitOfWork();
+            UnitOfWork uow = domainModule.unitOfWorkFactory().newUnitOfWork();
             EntityBuilder<PretextEntity> builder = uow.newEntityBuilder( PretextEntity.class );
             PretextEntity pretext = builder.instance();
             pretext.reason().set( "Testing purpose" );
             builder.newInstance();
             uow.complete();
 
-            uow = domainModule.newUnitOfWork();
+            uow = domainModule.unitOfWorkFactory().newUnitOfWork();
             QueryBuilder<PretextEntity> queryBuilder = domainModule.newQueryBuilder( PretextEntity.class );
             queryBuilder = queryBuilder.where( eq( templateFor( PretextEntity.class ).reason(), "Testing purpose" ) );
             Query<PretextEntity> query = uow.newQuery( queryBuilder );
@@ -107,7 +107,7 @@ public class Main
     {
         // EntityStore Data
         {
-            UnitOfWork uow = persistenceModule.newUnitOfWork();
+            UnitOfWork uow = persistenceModule.unitOfWorkFactory().newUnitOfWork();
             try {
                 SQLConfiguration config = uow.get( SQLConfiguration.class,
                                                    PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
@@ -134,7 +134,7 @@ public class Main
 
         // Indexing Data
         {
-            UnitOfWork uow = persistenceModule.newUnitOfWork();
+            UnitOfWork uow = persistenceModule.unitOfWorkFactory().newUnitOfWork();
             try {
                 SQLConfiguration config = uow.get( SQLConfiguration.class, PostgreSQLIndexQueryAssembler.DEFAULT_IDENTITY );
                 Connection connection = persistenceModule.findService( DataSource.class ).get().getConnection();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tests/performance/src/main/java/org/apache/zest/test/performance/entitystore/AbstractEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/main/java/org/apache/zest/test/performance/entitystore/AbstractEntityStorePerformanceTest.java b/tests/performance/src/main/java/org/apache/zest/test/performance/entitystore/AbstractEntityStorePerformanceTest.java
index b35ace8..93eafd0 100644
--- a/tests/performance/src/main/java/org/apache/zest/test/performance/entitystore/AbstractEntityStorePerformanceTest.java
+++ b/tests/performance/src/main/java/org/apache/zest/test/performance/entitystore/AbstractEntityStorePerformanceTest.java
@@ -25,16 +25,16 @@ import java.io.FileWriter;
 import java.io.IOException;
 import java.util.Random;
 import java.util.concurrent.Callable;
-import org.junit.Before;
-import org.junit.Test;
+import org.apache.zest.api.service.ServiceFinder;
 import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.bootstrap.ApplicationAssemblerAdapter;
 import org.apache.zest.bootstrap.Assembler;
-import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.Energy4Java;
-import org.apache.zest.bootstrap.ModuleAssembly;
+import org.junit.Before;
+import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,7 +49,8 @@ public abstract class AbstractEntityStorePerformanceTest
     private final Assembler infrastructure;
     private final Logger logger;
     private Application application;
-    protected Module module;
+    protected UnitOfWorkFactory uowf;
+    protected ServiceFinder serviceFinder;
 
     private final int ITERATIONS = 20000;
 
@@ -66,23 +67,15 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            Assembler assembler = new Assembler()
-            {
-                @Override
-                public void assemble( ModuleAssembly module )
-                    throws AssemblyException
-                {
-                    module.entities( SimpleProduct.class );
-                }
-            };
+            Assembler assembler = module -> module.entities( SimpleProduct.class );
             createZestRuntime( assembler );
 
             for( int i = 0; i < 10000; i++ )
             {
-                try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "Warmup " + i ) ) )
+                try (UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Warmup " + i ) ))
                 {
                     SimpleProduct product = uow.newEntity( SimpleProduct.class );
-                    String id = product.identity().get();
+                    product.identity().get();
                 }
             }
         }
@@ -103,42 +96,28 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            Assembler assembler = new Assembler()
-            {
-                @Override
-                public void assemble( ModuleAssembly module )
-                    throws AssemblyException
-                {
-                    module.entities( SimpleProduct.class );
-                }
-            };
+            Assembler assembler = module -> module.entities( SimpleProduct.class );
             createZestRuntime( assembler );
 
-            profile( new Callable<Void>()
-            {
-                @Override
-                public Void call()
-                    throws Exception
+            profile( () -> {
+                Report report = new Report( storeName );
+                report.start( "createEntityWithSingleProperty" );
+                for( int i = 0; i < ITERATIONS; i++ )
                 {
-                    Report report = new Report( storeName );
-                    report.start( "createEntityWithSingleProperty" );
-                    for( int i = 0; i < ITERATIONS; i++ )
+                    try (UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "createEntityWithSingleProperty " + i ) ))
                     {
-                        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "createEntityWithSingleProperty " + i ) ) )
-                        {
-                            SimpleProduct product = uow.newEntity( SimpleProduct.class );
-                            String id = product.identity().get();
-                            uow.complete();
-                        }
-                        if( i % 1000 == 0 )
-                        {
-                            logger.info( "Iteration {}", i );
-                        }
+                        SimpleProduct product = uow.newEntity( SimpleProduct.class );
+                        product.identity().get();
+                        uow.complete();
+                    }
+                    if( i % 1000 == 0 )
+                    {
+                        logger.info( "Iteration {}", i );
                     }
-                    report.stop( ITERATIONS );
-                    writeReport( report );
-                    return null;
                 }
+                report.stop( ITERATIONS );
+                writeReport( report );
+                return null;
             } );
         }
         finally
@@ -153,42 +132,28 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            Assembler assembler = new Assembler()
-            {
-                @Override
-                public void assemble( ModuleAssembly module )
-                    throws AssemblyException
-                {
-                    module.entities( SimpleProduct.class );
-                }
-            };
+            Assembler assembler = module -> module.entities( SimpleProduct.class );
             createZestRuntime( assembler );
-            profile( new Callable<Void>()
-            {
-                @Override
-                public Void call()
-                    throws Exception
+            profile( () -> {
+                Report report = new Report( storeName );
+                report.start( "createEntityInBulkWithSingleProperty" );
+                int bulk = 0;
+                UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "createEntityInBulkWithSingleProperty " + bulk ) );
+                for( int i = 0; i < ITERATIONS; i++ )
                 {
-                    Report report = new Report( storeName );
-                    report.start( "createEntityInBulkWithSingleProperty" );
-                    int bulk = 0;
-                    UnitOfWork uow = module.newUnitOfWork( newUsecase( "createEntityInBulkWithSingleProperty " + bulk ) );
-                    for( int i = 0; i < ITERATIONS; i++ )
+                    SimpleProduct product = uow.newEntity( SimpleProduct.class );
+                    product.identity().get();
+                    if( i % 1000 == 0 )
                     {
-                        SimpleProduct product = uow.newEntity( SimpleProduct.class );
-                        String id = product.identity().get();
-                        if( i % 1000 == 0 )
-                        {
-                            uow.complete();
-                            bulk++;
-                            uow = module.newUnitOfWork( newUsecase( "createEntityInBulkWithSingleProperty " + bulk ) );
-                        }
+                        uow.complete();
+                        bulk++;
+                        uow = uowf.newUnitOfWork( newUsecase( "createEntityInBulkWithSingleProperty " + bulk ) );
                     }
-                    uow.complete();
-                    report.stop( ITERATIONS );
-                    writeReport( report );
-                    return null;
                 }
+                uow.complete();
+                report.stop( ITERATIONS );
+                writeReport( report );
+                return null;
             } );
         }
         finally
@@ -203,37 +168,23 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            Assembler assembler = new Assembler()
-            {
-                @Override
-                public void assemble( ModuleAssembly module )
-                    throws AssemblyException
-                {
-                    module.entities( ComplexProduct.class );
-                }
-            };
+            Assembler assembler = module -> module.entities( ComplexProduct.class );
             createZestRuntime( assembler );
-            profile( new Callable<Void>()
-            {
-                @Override
-                public Void call()
-                    throws Exception
+            profile( () -> {
+                Report report = new Report( storeName );
+                report.start( "createEntityWithComplexType" );
+                for( int i = 0; i < ITERATIONS; i++ )
                 {
-                    Report report = new Report( storeName );
-                    report.start( "createEntityWithComplexType" );
-                    for( int i = 0; i < ITERATIONS; i++ )
+                    try (UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "createEntityWithComplexType " + i ) ))
                     {
-                        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "createEntityWithComplexType " + i ) ) )
-                        {
-                            ComplexProduct product = uow.newEntity( ComplexProduct.class );
-                            String id = product.identity().get();
-                            uow.complete();
-                        }
+                        ComplexProduct product = uow.newEntity( ComplexProduct.class );
+                        product.identity().get();
+                        uow.complete();
                     }
-                    report.stop( ITERATIONS );
-                    writeReport( report );
-                    return null;
                 }
+                report.stop( ITERATIONS );
+                writeReport( report );
+                return null;
             } );
         }
         finally
@@ -248,42 +199,28 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            Assembler assembler = new Assembler()
-            {
-                @Override
-                public void assemble( ModuleAssembly module )
-                    throws AssemblyException
-                {
-                    module.entities( ComplexProduct.class );
-                }
-            };
+            Assembler assembler = module -> module.entities( ComplexProduct.class );
             createZestRuntime( assembler );
-            profile( new Callable<Void>()
-            {
-                @Override
-                public Void call()
-                    throws Exception
+            profile( () -> {
+                Report report = new Report( storeName );
+                report.start( "createEntityInBulkWithComplexType" );
+                int bulk = 0;
+                UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "createEntityInBulkWithComplexType " + bulk ) );
+                for( int i = 0; i < ITERATIONS; i++ )
                 {
-                    Report report = new Report( storeName );
-                    report.start( "createEntityInBulkWithComplexType" );
-                    int bulk = 0;
-                    UnitOfWork uow = module.newUnitOfWork( newUsecase( "createEntityInBulkWithComplexType " + bulk ) );
-                    for( int i = 0; i < ITERATIONS; i++ )
+                    ComplexProduct product = uow.newEntity( ComplexProduct.class );
+                    product.identity().get();
+                    if( i % 1000 == 0 )
                     {
-                        ComplexProduct product = uow.newEntity( ComplexProduct.class );
-                        String id = product.identity().get();
-                        if( i % 1000 == 0 )
-                        {
-                            uow.complete();
-                            bulk++;
-                            uow = module.newUnitOfWork( newUsecase( "createEntityInBulkWithComplexType " + bulk ) );
-                        }
+                        uow.complete();
+                        bulk++;
+                        uow = uowf.newUnitOfWork( newUsecase( "createEntityInBulkWithComplexType " + bulk ) );
                     }
-                    uow.complete();
-                    report.stop( ITERATIONS );
-                    writeReport( report );
-                    return null;
                 }
+                uow.complete();
+                report.stop( ITERATIONS );
+                writeReport( report );
+                return null;
             } );
         }
         finally
@@ -298,19 +235,11 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            Assembler assembler = new Assembler()
-            {
-                @Override
-                public void assemble( ModuleAssembly module )
-                    throws AssemblyException
-                {
-                    module.entities( ComplexProduct.class );
-                }
-            };
+            Assembler assembler = module -> module.entities( ComplexProduct.class );
             createZestRuntime( assembler );
             {
                 int bulk = 0;
-                UnitOfWork uow = module.newUnitOfWork( newUsecase( "readEntityWithComplexType PREPARE " + bulk ) );
+                UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "readEntityWithComplexType PREPARE " + bulk ) );
                 for( int i = 0; i < ITERATIONS; i++ )
                 {
                     ComplexProduct product = uow.newEntity( ComplexProduct.class, "product" + i );
@@ -320,42 +249,34 @@ public abstract class AbstractEntityStorePerformanceTest
                     {
                         uow.complete();
                         bulk++;
-                        uow = module.newUnitOfWork( newUsecase( "readEntityWithComplexType PREPARE " + bulk ) );
+                        uow = uowf.newUnitOfWork( newUsecase( "readEntityWithComplexType PREPARE " + bulk ) );
                     }
                 }
                 uow.complete();
             }
 
-            profile( new Callable<Void>()
-            {
-                @Override
-                public Void call()
-                    throws Exception
+            profile( () -> {
+                Report report = new Report( storeName );
+                int bulk = 0;
+                UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "readEntityWithComplexType " + bulk ) );
+                Random rnd = new Random();
+                report.start( "readEntityWithComplexType" );
+                String id = rnd.nextInt( ITERATIONS ) + "";
+                for( int i = 0; i < ITERATIONS; i++ )
                 {
-                    Report report = new Report( storeName );
-                    int bulk = 0;
-                    UnitOfWork uow = module.newUnitOfWork( newUsecase( "readEntityWithComplexType " + bulk ) );
-                    Random rnd = new Random();
-                    report.start( "readEntityWithComplexType" );
-                    String id = rnd.nextInt( ITERATIONS ) + "";
-                    for( int i = 0; i < ITERATIONS; i++ )
+                    ComplexProduct product = uow.get( ComplexProduct.class, "product" + id );
+                    product.name().get();
+                    if( i % 100 == 0 )
                     {
-                        ComplexProduct product = uow.get( ComplexProduct.class, "product" + id );
-
-                        String name = product.name().get();
-
-                        if( i % 100 == 0 )
-                        {
-                            uow.discard();
-                            bulk++;
-                            uow = module.newUnitOfWork( newUsecase( "readEntityWithComplexType " + bulk ) );
-                        }
+                        uow.discard();
+                        bulk++;
+                        uow = uowf.newUnitOfWork( newUsecase( "readEntityWithComplexType " + bulk ) );
                     }
-                    uow.complete();
-                    report.stop( ITERATIONS );
-                    writeReport( report );
-                    return null;
                 }
+                uow.complete();
+                report.stop( ITERATIONS );
+                writeReport( report );
+                return null;
             } );
         }
         finally
@@ -376,10 +297,13 @@ public abstract class AbstractEntityStorePerformanceTest
         throws IOException
     {
         File dir = new File( "build/reports/perf/" );
-        dir.mkdirs();
+        if( !dir.mkdirs() )
+        {
+            System.out.println( "Couldn't create Performance result directory." );
+        }
         String name = dir.getAbsolutePath() + "/result-" + report.name() + ".xml";
         FileWriter writer = new FileWriter( name, true );
-        try( BufferedWriter out = new BufferedWriter( writer ) )
+        try (BufferedWriter out = new BufferedWriter( writer ))
         {
             report.writeTo( out );
             out.flush();
@@ -392,20 +316,21 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         Energy4Java zest = new Energy4Java();
         Assembler[][][] assemblers = new Assembler[][][]
-        {
             {
                 {
-                    infrastructure, testSetup
+                    {
+                        infrastructure, testSetup
+                    }
                 }
-            }
-        };
+            };
         application = zest.newApplication( new ApplicationAssemblerAdapter( assemblers )
         {
         } );
         application.activate();
 
         Module moduleInstance = application.findModule( "Layer 1", "Module 1" );
-        module = moduleInstance;
+        uowf = moduleInstance.unitOfWorkFactory();
+        serviceFinder = moduleInstance;
     }
 
     protected void cleanUp()
@@ -413,10 +338,10 @@ public abstract class AbstractEntityStorePerformanceTest
     {
         try
         {
-            if( module != null && module.isUnitOfWorkActive() )
+            if( uowf != null && uowf.isUnitOfWorkActive() )
             {
                 UnitOfWork current;
-                while( module.isUnitOfWorkActive() && ( current = module.currentUnitOfWork() ) != null )
+                while( uowf.isUnitOfWorkActive() && ( current = uowf.currentUnitOfWork() ) != null )
                 {
                     if( current.isOpen() )
                     {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
index 180ee27..3abd538 100644
--- a/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
@@ -87,17 +87,17 @@ public class DerbySQLEntityStorePerformanceTest
     protected void cleanUp()
         throws Exception
     {
-        if( module == null )
+        if( uowf == null )
         {
             return;
         }
-        UnitOfWork uow = this.module.newUnitOfWork( UsecaseBuilder.newUsecase(
+        UnitOfWork uow = this.uowf.newUnitOfWork( UsecaseBuilder.newUsecase(
             "Delete " + getClass().getSimpleName() + " test data" ) );
         try
         {
             SQLConfiguration config = uow.get( SQLConfiguration.class,
                                                DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
-            Connection connection = module.findService( DataSource.class ).get().getConnection();
+            Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
             String schemaName = config.schemaName().get();
             if( schemaName == null )
             {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
index 47238a8..3e04c01 100644
--- a/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/zest/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
@@ -115,7 +115,7 @@ public class PostgreSQLEntityStorePerformanceTest
             application.activate();
 
             Module moduleInstance = application.findModule( "Layer 1", "config" );
-            UnitOfWorkFactory uowf = moduleInstance;
+            UnitOfWorkFactory uowf = moduleInstance.unitOfWorkFactory();
             UnitOfWork uow = uowf.newUnitOfWork();
             try
             {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tests/performance/src/perf/java/org/apache/zest/test/performance/indexing/rdf/QueryPerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/zest/test/performance/indexing/rdf/QueryPerformanceTest.java b/tests/performance/src/perf/java/org/apache/zest/test/performance/indexing/rdf/QueryPerformanceTest.java
index 321f30f..912172e 100644
--- a/tests/performance/src/perf/java/org/apache/zest/test/performance/indexing/rdf/QueryPerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/zest/test/performance/indexing/rdf/QueryPerformanceTest.java
@@ -20,6 +20,8 @@ package org.apache.zest.test.performance.indexing.rdf;
 
 import java.io.File;
 import org.apache.derby.iapi.services.io.FileUtil;
+import org.apache.zest.api.query.QueryBuilderFactory;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -70,6 +72,7 @@ public class QueryPerformanceTest
 
     private Application application;
     private Module module;
+    private UnitOfWorkFactory uowf;
     private static final String QUERY1 = "PREFIX ns0: <urn:zest:type:org.apache.zest.api.entity.Identity#> \n"
                                          + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
                                          + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
@@ -136,6 +139,7 @@ public class QueryPerformanceTest
         module = application.findModule( LAYER_DOMAIN, MODULE_DOMAIN );
         application.activate();
         indexingDataDir = module.findService( RdfIndexingService.class ).get().dataDir();
+        uowf = module.unitOfWorkFactory();
     }
 
     @After
@@ -196,7 +200,7 @@ public class QueryPerformanceTest
     private LeadRepository populateEntityStore()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             LeadRepository leadRepo = module.findService( LeadRepositoryService.class ).get();
@@ -212,7 +216,7 @@ public class QueryPerformanceTest
                     {
                         System.out.print( "\r" + i );
                         uow.complete();
-                        uow = module.newUnitOfWork();
+                        uow = uowf.newUnitOfWork();
                     }
                     leadFactory.create( "Lead" + i );
                 }
@@ -237,7 +241,7 @@ public class QueryPerformanceTest
     {
         long start;
         long end;
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             start = System.currentTimeMillis();
             Lead lead = leadRepo.findByName( nameOfEntity );
@@ -258,7 +262,7 @@ public class QueryPerformanceTest
     {
         long start;
         long end;
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             start = System.currentTimeMillis();
             Lead lead = leadRepo.findByFixedQuery( queryName );
@@ -338,12 +342,12 @@ public class QueryPerformanceTest
         implements LeadEntityFactory
     {
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Override
         public Lead create( String name )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             EntityBuilder<LeadEntity> builder = uow.newEntityBuilder( LeadEntity.class );
             Lead prototype = builder.instanceFor( LeadEntity.class );
             prototype.name().set( name );
@@ -368,21 +372,24 @@ public class QueryPerformanceTest
         implements LeadRepository
     {
         @Structure
-        private Module module;
+        private QueryBuilderFactory qbf;
+
+        @Structure
+        private UnitOfWorkFactory uowf;
 
         @Override
         public Lead findByFixedQuery( String queryString )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
-            Query<Lead> query = uow.newQuery( module.newQueryBuilder( Lead.class ).where( SesameExpressions.sparql( queryString ) ) );
+            UnitOfWork uow = uowf.currentUnitOfWork();
+            Query<Lead> query = uow.newQuery( qbf.newQueryBuilder( Lead.class ).where( SesameExpressions.sparql( queryString ) ) );
             return query.find();
         }
 
         @Override
         public Lead findByName( String name )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
-            QueryBuilder<Lead> builder = module.newQueryBuilder( Lead.class );
+            UnitOfWork uow = uowf.currentUnitOfWork();
+            QueryBuilder<Lead> builder = qbf.newQueryBuilder( Lead.class );
             Lead template = templateFor( Lead.class );
 
             Query<Lead> query = uow.newQuery( builder.where( eq( template.name(), name ) ) );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tools/envisage/src/main/resources/org/apache/zest/envisage/tree/TreeModelCellRenderer.properties
----------------------------------------------------------------------
diff --git a/tools/envisage/src/main/resources/org/apache/zest/envisage/tree/TreeModelCellRenderer.properties b/tools/envisage/src/main/resources/org/apache/zest/envisage/tree/TreeModelCellRenderer.properties
index b694372..4e5c3f6 100644
--- a/tools/envisage/src/main/resources/org/apache/zest/envisage/tree/TreeModelCellRenderer.properties
+++ b/tools/envisage/src/main/resources/org/apache/zest/envisage/tree/TreeModelCellRenderer.properties
@@ -15,7 +15,7 @@
 
 ICON_Application=application.png
 ICON_Layer=layer.png
-ICON_Module=module.png
+ICON_Module=unitOfWorkFactory.png
 ICON_Service=service.png
 ICON_ImportedService=importedService.png
 ICON_Entity=entity.png

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tools/envisage/src/test/java/org/apache/zest/envisage/sample/EnvisageSample.java
----------------------------------------------------------------------
diff --git a/tools/envisage/src/test/java/org/apache/zest/envisage/sample/EnvisageSample.java b/tools/envisage/src/test/java/org/apache/zest/envisage/sample/EnvisageSample.java
index ddf04b3..80a2cd6 100644
--- a/tools/envisage/src/test/java/org/apache/zest/envisage/sample/EnvisageSample.java
+++ b/tools/envisage/src/test/java/org/apache/zest/envisage/sample/EnvisageSample.java
@@ -75,7 +75,7 @@ public class EnvisageSample
 
     public void createTestData()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             createCar( "Volvo", "S80", 2007 );
@@ -101,7 +101,7 @@ public class EnvisageSample
 
     private String createCar( String manufacturer, String model, int year )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<Car> builder = uow.newEntityBuilder( Car.class );
         Car prototype = builder.instanceFor( CarEntity.class );
         prototype.manufacturer().set( manufacturer );
@@ -113,7 +113,7 @@ public class EnvisageSample
 
     private String createAnimal( String name, String sound )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<Animal> builder = uow.newEntityBuilder( Animal.class );
         Animal prototype = builder.instanceFor( AnimalEntity.class );
         prototype.name().set( name );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tools/model-detail/src/test/java/org/apache/zest/tools/model/VisitableDetailTest.java
----------------------------------------------------------------------
diff --git a/tools/model-detail/src/test/java/org/apache/zest/tools/model/VisitableDetailTest.java b/tools/model-detail/src/test/java/org/apache/zest/tools/model/VisitableDetailTest.java
index e91636b..98e4a7d 100644
--- a/tools/model-detail/src/test/java/org/apache/zest/tools/model/VisitableDetailTest.java
+++ b/tools/model-detail/src/test/java/org/apache/zest/tools/model/VisitableDetailTest.java
@@ -51,24 +51,18 @@ public class VisitableDetailTest
         throws AssemblyException, ActivationException
     {
         ApplicationDescriptor application = new Energy4Java().newApplicationModel(
-            new ApplicationAssembler()
-            {
-                @Override
-                public ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
-                throws AssemblyException
-                {
-                    ApplicationAssembly app = applicationFactory.newApplicationAssembly();
-                    app.setName( "UnderTestApp" );
-                    app.withActivators( ApplicationActivator.class );
+            applicationFactory -> {
+                ApplicationAssembly app = applicationFactory.newApplicationAssembly();
+                app.setName( "UnderTestApp" );
+                app.withActivators( ApplicationActivator.class );
 
-                    LayerAssembly layer = app.layer( "LayerName" );
-                    layer.withActivators( LayerActivator.class );
+                LayerAssembly layer = app.layer( "LayerName" );
+                layer.withActivators( LayerActivator.class );
 
-                    ModuleAssembly module = layer.module( "ModuleName" );
-                    module.withActivators( ModuleActivator.class );
+                ModuleAssembly module = layer.module( "ModuleName" );
+                module.withActivators( ModuleActivator.class );
 
-                    return app;
-                }
+                return app;
             }
         );
         ApplicationDetailDescriptor detail = createApplicationDetailDescriptor( application );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tutorials/hello/src/test/java/org/apache/zest/tutorials/hello/HelloTest4.java
----------------------------------------------------------------------
diff --git a/tutorials/hello/src/test/java/org/apache/zest/tutorials/hello/HelloTest4.java b/tutorials/hello/src/test/java/org/apache/zest/tutorials/hello/HelloTest4.java
index 3ce8125..8c31e1b 100644
--- a/tutorials/hello/src/test/java/org/apache/zest/tutorials/hello/HelloTest4.java
+++ b/tutorials/hello/src/test/java/org/apache/zest/tutorials/hello/HelloTest4.java
@@ -37,7 +37,7 @@ public class HelloTest4 extends AbstractZestTest
     @Test
     public void givenHelloValueInitializedToHelloWorldWhenCallingSayExpectHelloWorld()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Hello> builder = uow.newEntityBuilder( Hello.class, "123" );
@@ -45,7 +45,7 @@ public class HelloTest4 extends AbstractZestTest
             builder.instanceFor( Hello.State.class ).name().set( "World" );
             builder.newInstance();
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             Hello underTest = uow.get( Hello.class, "123" );
             String result = underTest.say();
             uow.complete();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/tutorials/introduction/thirtyminutes/src/main/java/org/apache/zest/demo/thirtyminutes/ThirtyMinutesDocs.java
----------------------------------------------------------------------
diff --git a/tutorials/introduction/thirtyminutes/src/main/java/org/apache/zest/demo/thirtyminutes/ThirtyMinutesDocs.java b/tutorials/introduction/thirtyminutes/src/main/java/org/apache/zest/demo/thirtyminutes/ThirtyMinutesDocs.java
index d71b98c..26a0a92 100644
--- a/tutorials/introduction/thirtyminutes/src/main/java/org/apache/zest/demo/thirtyminutes/ThirtyMinutesDocs.java
+++ b/tutorials/introduction/thirtyminutes/src/main/java/org/apache/zest/demo/thirtyminutes/ThirtyMinutesDocs.java
@@ -33,10 +33,11 @@ import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.property.Property;
 import org.apache.zest.api.query.Query;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.query.QueryBuilderFactory;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.api.value.ValueComposite;
 import org.apache.zest.demo.tenminute.Confirmable;
 import org.apache.zest.demo.tenminute.HasCustomer;
@@ -56,7 +57,9 @@ import org.apache.zest.api.query.QueryBuilder;
 // END SNIPPET: 6
 public class ThirtyMinutesDocs
 {
-    Module module;
+    private QueryBuilderFactory queryBuilderFactory;
+    private ValueBuilderFactory valueBuilderFactory;
+    private UnitOfWorkFactory unitOfWorkFactory;
 
 // START SNIPPET: 6
     @Structure private UnitOfWorkFactory uowFactory; //Injected
@@ -65,7 +68,7 @@ public class ThirtyMinutesDocs
     {
 // START SNIPPET: 6
         UnitOfWork uow = uowFactory.currentUnitOfWork();
-        QueryBuilder<Order> builder = module.newQueryBuilder( Order.class );
+        QueryBuilder<Order> builder = queryBuilderFactory.newQueryBuilder( Order.class );
 
         String orderNumber = "12345";
         HasSequenceNumber template = templateFor( HasSequenceNumber.class );
@@ -94,10 +97,10 @@ public class ThirtyMinutesDocs
 
     {
         Report report = null;
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = unitOfWorkFactory.currentUnitOfWork();
 
 // START SNIPPET: 7
-        QueryBuilder<Order> builder = module.newQueryBuilder( Order.class );
+        QueryBuilder<Order> builder = queryBuilderFactory.newQueryBuilder( Order.class );
 
         Calendar cal = Calendar.getInstance();
         cal.setTime( new Date() );
@@ -116,10 +119,10 @@ public class ThirtyMinutesDocs
 
     {
         Report report = null;
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = unitOfWorkFactory.currentUnitOfWork();
 
 // START SNIPPET: 8
-        QueryBuilder<HasCustomer> builder = module.newQueryBuilder( HasCustomer.class );
+        QueryBuilder<HasCustomer> builder = queryBuilderFactory.newQueryBuilder( HasCustomer.class );
 
         Calendar cal = Calendar.getInstance();
         cal.setTime( new Date() );
@@ -200,7 +203,7 @@ public class ThirtyMinutesDocs
         private Action<M> addAction( M item, Action.Type type )
         {
             ValueBuilder<Action> builder =
-                    module.newValueBuilder(Action.class);       // [4]
+                    valueBuilderFactory.newValueBuilder( Action.class);       // [4]
             Action<M> prototype = builder.prototypeFor( Action.class );
             prototype.item().set( item );
             prototype.action().set( type );


[7/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/ModuleUnitOfWork.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/ModuleUnitOfWork.java b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/ModuleUnitOfWork.java
new file mode 100755
index 0000000..118510f
--- /dev/null
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/ModuleUnitOfWork.java
@@ -0,0 +1,777 @@
+/*
+ * 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.zest.runtime.unitofwork;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import org.apache.zest.api.association.AssociationDescriptor;
+import org.apache.zest.api.association.AssociationStateHolder;
+import org.apache.zest.api.common.QualifiedName;
+import org.apache.zest.api.composite.Composite;
+import org.apache.zest.api.entity.EntityBuilder;
+import org.apache.zest.api.entity.EntityComposite;
+import org.apache.zest.api.entity.EntityDescriptor;
+import org.apache.zest.api.entity.EntityReference;
+import org.apache.zest.api.entity.Identity;
+import org.apache.zest.api.entity.IdentityGenerator;
+import org.apache.zest.api.entity.LifecycleException;
+import org.apache.zest.api.injection.scope.Service;
+import org.apache.zest.api.injection.scope.Structure;
+import org.apache.zest.api.injection.scope.Uses;
+import org.apache.zest.api.property.Property;
+import org.apache.zest.api.property.PropertyDescriptor;
+import org.apache.zest.api.property.StateHolder;
+import org.apache.zest.api.query.Query;
+import org.apache.zest.api.query.QueryBuilder;
+import org.apache.zest.api.query.QueryExecutionException;
+import org.apache.zest.api.query.grammar.OrderBy;
+import org.apache.zest.api.service.NoSuchServiceException;
+import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.ConcurrentEntityModificationException;
+import org.apache.zest.api.unitofwork.EntityTypeNotFoundException;
+import org.apache.zest.api.unitofwork.NoSuchEntityException;
+import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkCallback;
+import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.api.usecase.Usecase;
+import org.apache.zest.api.util.NullArgumentException;
+import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueComposite;
+import org.apache.zest.functional.Iterables;
+import org.apache.zest.runtime.association.AssociationInstance;
+import org.apache.zest.runtime.association.ManyAssociationInstance;
+import org.apache.zest.runtime.association.NamedAssociationInstance;
+import org.apache.zest.runtime.composite.FunctionStateResolver;
+import org.apache.zest.runtime.entity.EntityInstance;
+import org.apache.zest.runtime.entity.EntityModel;
+import org.apache.zest.runtime.property.PropertyModel;
+import org.apache.zest.runtime.value.ValueInstance;
+import org.apache.zest.spi.entity.EntityState;
+import org.apache.zest.spi.entity.EntityStatus;
+import org.apache.zest.spi.entity.NamedAssociationState;
+import org.apache.zest.spi.entitystore.EntityStore;
+import org.apache.zest.spi.structure.ModelModule;
+import org.apache.zest.spi.module.ModuleSpi;
+import org.apache.zest.spi.query.EntityFinder;
+import org.apache.zest.spi.query.EntityFinderException;
+import org.apache.zest.spi.query.QueryBuilderSPI;
+import org.apache.zest.spi.query.QuerySource;
+
+import static org.apache.zest.api.entity.EntityReference.parseEntityReference;
+
+/**
+ * JAVADOC
+ */
+public class ModuleUnitOfWork
+    implements UnitOfWork
+{
+    private static final QualifiedName IDENTITY_STATE_NAME;
+
+    static
+    {
+        try
+        {
+            IDENTITY_STATE_NAME = QualifiedName.fromAccessor( Identity.class.getMethod( "identity" ) );
+        }
+        catch( NoSuchMethodException e )
+        {
+            throw new InternalError( "Zest Core Runtime codebase is corrupted. Contact Zest team: ModuleUnitOfWork" );
+        }
+    }
+
+    @Uses
+    private UnitOfWorkInstance uow;
+
+    @Structure
+    private ModuleSpi module;
+
+    @Service
+    private UnitOfWorkFactory unitOfWorkFactory;
+
+    public Module module()
+    {
+        return module;
+    }
+
+    public UnitOfWorkInstance instance()
+    {
+        return uow;
+    }
+
+    @Override
+    public UnitOfWorkFactory unitOfWorkFactory()
+    {
+        return unitOfWorkFactory;
+    }
+
+    @Override
+    public long currentTime()
+    {
+        return uow.currentTime();
+    }
+
+    @Override
+    public Usecase usecase()
+    {
+        return uow.usecase();
+    }
+
+    @Override
+    public <T> T metaInfo( Class<T> infoType )
+    {
+        return uow.metaInfo().get( infoType );
+    }
+
+    @Override
+    public void setMetaInfo( Object metaInfo )
+    {
+        uow.metaInfo().set( metaInfo );
+    }
+
+    @Override
+    @SuppressWarnings( { "raw", "unchecked" } )
+    public <T> Query<T> newQuery( QueryBuilder<T> queryBuilder )
+    {
+        QueryBuilderSPI queryBuilderSPI = (QueryBuilderSPI) queryBuilder;
+
+        return queryBuilderSPI.newQuery( new UoWQuerySource( this ) );
+    }
+
+    @Override
+    public <T> T newEntity( Class<T> type )
+        throws EntityTypeNotFoundException, LifecycleException
+    {
+        return newEntity( type, null );
+    }
+
+    @Override
+    public <T> T newEntity( Class<T> type, String identity )
+        throws EntityTypeNotFoundException, LifecycleException
+    {
+        return newEntityBuilder( type, identity ).newInstance();
+    }
+
+    @Override
+    public <T> EntityBuilder<T> newEntityBuilder( Class<T> type )
+        throws EntityTypeNotFoundException
+    {
+        return newEntityBuilder( type, null );
+    }
+
+    @Override
+    public <T> EntityBuilder<T> newEntityBuilder( Class<T> type, String identity )
+        throws EntityTypeNotFoundException
+    {
+        ModelModule<EntityDescriptor> model = module.typeLookup().lookupEntityModel( type );
+
+        if( model == null )
+        {
+            throw new EntityTypeNotFoundException( type.getName(),
+                                                   module.name(),
+                                                   module.findVisibleEntityTypes().map( ModelModule.toStringFunction )
+            );
+        }
+
+        EntityStore entityStore = ((ModuleSpi) model.module()).entityStore();
+
+        // Generate id if necessary
+        if( identity == null )
+        {
+            IdentityGenerator idGen = ((ModuleSpi) model.module()).identityGenerator();
+            if( idGen == null )
+            {
+                throw new NoSuchServiceException( IdentityGenerator.class.getName(), model.module().name() );
+            }
+            identity = idGen.generate( model.model().types().findFirst().orElse( null ) );
+        }
+        EntityBuilder<T> builder;
+
+        builder = new EntityBuilderInstance<>( model,
+                                               this,
+                                               uow.getEntityStoreUnitOfWork( entityStore ),
+                                               identity );
+        return builder;
+    }
+
+    @Override
+    public <T> EntityBuilder<T> newEntityBuilderWithState(
+        Class<T> type,
+        Function<PropertyDescriptor, Object> propertyFunction,
+        Function<AssociationDescriptor, EntityReference> associationFunction,
+        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssociationFunction,
+        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssociationFunction
+    )
+        throws EntityTypeNotFoundException
+    {
+        return newEntityBuilderWithState( type, null,
+                                          propertyFunction,
+                                          associationFunction,
+                                          manyAssociationFunction,
+                                          namedAssociationFunction );
+    }
+
+    @Override
+    public <T> EntityBuilder<T> newEntityBuilderWithState(
+        Class<T> type, String identity,
+        Function<PropertyDescriptor, Object> propertyFunction,
+        Function<AssociationDescriptor, EntityReference> associationFunction,
+        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssociationFunction,
+        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssociationFunction
+    )
+        throws EntityTypeNotFoundException
+    {
+        NullArgumentException.validateNotNull( "propertyFunction", propertyFunction );
+        NullArgumentException.validateNotNull( "associationFunction", associationFunction );
+        NullArgumentException.validateNotNull( "manyAssociationFunction", manyAssociationFunction );
+        NullArgumentException.validateNotNull( "namedAssociationFunction", namedAssociationFunction );
+
+        ModelModule<EntityDescriptor> model = module.typeLookup().lookupEntityModel( type );
+
+        if( model == null )
+        {
+            throw new EntityTypeNotFoundException( type.getName(),
+                                                   module.name(),
+                                                   module.findVisibleEntityTypes().map( ModelModule.toStringFunction )
+            );
+        }
+
+        EntityStore entityStore = model.module().entityStore();
+
+        FunctionStateResolver stateResolver = new FunctionStateResolver(
+            propertyFunction, associationFunction, manyAssociationFunction, namedAssociationFunction
+        );
+
+        if( identity == null )
+        {
+            // Use identity from StateResolver if available
+            PropertyModel identityModel = (PropertyModel) model.model().state().findPropertyModelByQualifiedName( IDENTITY_STATE_NAME );
+            identity = (String) stateResolver.getPropertyState( identityModel );
+            if( identity == null )
+            {
+                // Generate identity
+                IdentityGenerator idGen = model.module().identityGenerator();
+                if( idGen == null )
+                {
+                    throw new NoSuchServiceException( IdentityGenerator.class.getName(), model.module().name() );
+                }
+                identity = idGen.generate( model.model().types().findFirst().orElse( null ));
+            }
+        }
+
+        return new EntityBuilderInstance<>( model,
+                                            this,
+                                            uow.getEntityStoreUnitOfWork( entityStore ),
+                                            identity,
+                                            stateResolver );
+    }
+
+    @Override
+    public <T> T get( Class<T> type, String identity )
+        throws EntityTypeNotFoundException, NoSuchEntityException
+    {
+        Iterable<ModelModule<EntityDescriptor>> models = module.typeLookup().lookupEntityModels( type );
+
+        if( !models.iterator().hasNext() )
+        {
+            throw new EntityTypeNotFoundException( type.getName(),
+                                                   module.name(),
+                                                   ((ModuleSpi) module).findVisibleEntityTypes().map( ModelModule.toStringFunction )
+            );
+        }
+
+        return uow.get( parseEntityReference( identity ), this, models, type );
+    }
+
+    @Override
+    @SuppressWarnings( "unchecked" )
+    public <T> T get( T entity )
+        throws EntityTypeNotFoundException
+    {
+        EntityComposite entityComposite = (EntityComposite) entity;
+        EntityInstance compositeInstance = EntityInstance.entityInstanceOf( entityComposite );
+        ModelModule<EntityDescriptor> model = new ModelModule<>( compositeInstance.module(), compositeInstance.entityModel() );
+        Class<T> type = (Class<T>) compositeInstance.types().findFirst().orElse( null );
+        return uow.get( compositeInstance.identity(), this, Collections.singletonList( model ), type );
+    }
+
+    @Override
+    public void remove( Object entity )
+        throws LifecycleException
+    {
+        uow.checkOpen();
+
+        EntityComposite entityComposite = (EntityComposite) entity;
+
+        EntityInstance compositeInstance = EntityInstance.entityInstanceOf( entityComposite );
+
+        if( compositeInstance.status() == EntityStatus.NEW )
+        {
+            compositeInstance.remove( this );
+            uow.remove( compositeInstance.identity() );
+        }
+        else if( compositeInstance.status() == EntityStatus.LOADED || compositeInstance.status() == EntityStatus.UPDATED )
+        {
+            compositeInstance.remove( this );
+        }
+        else
+        {
+            throw new NoSuchEntityException( compositeInstance.identity(), compositeInstance.types(), usecase() );
+        }
+    }
+
+    @SuppressWarnings( "DuplicateThrows" )
+    @Override
+    public void complete()
+        throws UnitOfWorkCompletionException, ConcurrentEntityModificationException
+    {
+        uow.complete();
+    }
+
+    @Override
+    public void discard()
+    {
+        uow.discard();
+    }
+
+    @Override
+    public void close()
+    {
+        discard();
+    }
+
+    @Override
+    public boolean isOpen()
+    {
+        return uow.isOpen();
+    }
+
+    @Override
+    public boolean isPaused()
+    {
+        return uow.isPaused();
+    }
+
+    @Override
+    public void pause()
+    {
+        uow.pause();
+    }
+
+    @Override
+    public void resume()
+    {
+        uow.resume();
+    }
+
+    @Override
+    public void addUnitOfWorkCallback( UnitOfWorkCallback callback )
+    {
+        uow.addUnitOfWorkCallback( callback );
+    }
+
+    @Override
+    public void removeUnitOfWorkCallback( UnitOfWorkCallback callback )
+    {
+        uow.removeUnitOfWorkCallback( callback );
+    }
+
+    @Override
+    public boolean equals( Object o )
+    {
+        if( this == o )
+        {
+            return true;
+        }
+        if( o == null || getClass() != o.getClass() )
+        {
+            return false;
+        }
+
+        ModuleUnitOfWork that = (ModuleUnitOfWork) o;
+
+        return uow.equals( that.uow );
+    }
+
+    @Override
+    public int hashCode()
+    {
+        return uow.hashCode();
+    }
+
+    @Override
+    public String toString()
+    {
+        return uow.toString();
+    }
+
+    public void addEntity( EntityInstance instance )
+    {
+        uow.addEntity( instance );
+    }
+
+    @Override
+    public <T extends Identity> T toValue( Class<T> primaryType, T entityComposite )
+    {
+        Function<PropertyDescriptor, Object> propertyFunction = new ToValuePropertyMappingFunction( entityComposite );
+        Function<AssociationDescriptor, EntityReference> assocationFunction = new ToValueAssociationMappingFunction<>( entityComposite );
+        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssocFunction = new ToValueManyAssociationMappingFunction<>( entityComposite );
+        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssocFunction = new ToValueNameAssociationMappingFunction<>( entityComposite );
+
+        @SuppressWarnings( "unchecked" )
+        ValueBuilder<T> builder = module().newValueBuilderWithState(
+            primaryType, propertyFunction, assocationFunction, manyAssocFunction, namedAssocFunction );
+        return builder.newInstance();
+    }
+
+    @Override
+    public <T extends Identity> T toEntity( Class<T> primaryType, T valueComposite )
+    {
+        Function<PropertyDescriptor, Object> propertyFunction = new ToEntityPropertyMappingFunction<>( valueComposite );
+        Function<AssociationDescriptor, EntityReference> assocationFunction = new ToEntityAssociationMappingFunction<>( valueComposite );
+        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssocFunction = new ToEntityManyAssociationMappingFunction<>( valueComposite );
+        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssocFunction = new ToEntityNameAssociationMappingFunction<>( valueComposite );
+
+        String identity = valueComposite.identity().get();
+        try
+        {
+            T entity = get( primaryType, identity );
+            // If successful, then this entity is to by modified.
+            EntityInstance instance = EntityInstance.entityInstanceOf( (EntityComposite) entity );
+            EntityState state = instance.entityState();
+            FunctionStateResolver stateResolver = new FunctionStateResolver( propertyFunction,
+                                                                             assocationFunction,
+                                                                             manyAssocFunction,
+                                                                             namedAssocFunction );
+            EntityModel model = (EntityModel) EntityInstance.entityInstanceOf( (EntityComposite) entity ).descriptor();
+            stateResolver.populateState( model, state );
+            return entity;
+        }
+        catch( NoSuchEntityException e )
+        {
+            EntityBuilder<T> entityBuilder = newEntityBuilderWithState( primaryType,
+                                                                        identity,
+                                                                        propertyFunction,
+                                                                        assocationFunction,
+                                                                        manyAssocFunction,
+                                                                        namedAssocFunction );
+            return entityBuilder.newInstance();
+        }
+    }
+
+    private static class UoWQuerySource implements QuerySource
+    {
+        private final ModuleUnitOfWork moduleUnitOfWork;
+
+        private UoWQuerySource( ModuleUnitOfWork moduleUnitOfWork )
+        {
+            this.moduleUnitOfWork = moduleUnitOfWork;
+        }
+
+        @Override
+        public <T> T find( Class<T> resultType,
+                           Predicate<Composite> whereClause,
+                           Iterable<OrderBy> orderBySegments,
+                           Integer firstResult,
+                           Integer maxResults,
+                           Map<String, Object> variables
+        )
+        {
+            final EntityFinder entityFinder = moduleUnitOfWork.module().findService( EntityFinder.class ).get();
+
+            try
+            {
+                final EntityReference foundEntity = entityFinder.findEntity( resultType, whereClause, variables == null ? Collections
+                    .<String, Object>emptyMap() : variables );
+                if( foundEntity != null )
+                {
+                    try
+                    {
+                        return moduleUnitOfWork.get( resultType, foundEntity.identity() );
+                    }
+                    catch( NoSuchEntityException e )
+                    {
+                        return null; // Index is out of sync - entity has been removed
+                    }
+                }
+                // No entity was found
+                return null;
+            }
+            catch( EntityFinderException e )
+            {
+                throw new QueryExecutionException( "Finder caused exception", e );
+            }
+        }
+
+        @Override
+        public <T> long count( Class<T> resultType,
+                               Predicate<Composite> whereClause,
+                               Iterable<OrderBy> orderBySegments,
+                               Integer firstResult,
+                               Integer maxResults,
+                               Map<String, Object> variables
+        )
+        {
+            final EntityFinder entityFinder = moduleUnitOfWork.module().findService( EntityFinder.class ).get();
+
+            try
+            {
+                return entityFinder.countEntities( resultType, whereClause, variables == null ? Collections.<String, Object>emptyMap() : variables );
+            }
+            catch( EntityFinderException e )
+            {
+                e.printStackTrace();
+                return 0;
+            }
+        }
+
+        @Override
+        public <T> Iterator<T> iterator( final Class<T> resultType,
+                                         Predicate<Composite> whereClause,
+                                         Iterable<OrderBy> orderBySegments,
+                                         Integer firstResult,
+                                         Integer maxResults,
+                                         Map<String, Object> variables
+        )
+        {
+            final EntityFinder entityFinder = moduleUnitOfWork.module().findService( EntityFinder.class ).get();
+
+            try
+            {
+                final Iterator<EntityReference> foundEntities = entityFinder.findEntities( resultType,
+                                                                                           whereClause,
+                                                                                           Iterables.toArray( OrderBy.class, orderBySegments ),
+                                                                                           firstResult,
+                                                                                           maxResults,
+                                                                                           variables == null ? Collections
+                                                                                               .<String, Object>emptyMap() : variables )
+                    .iterator();
+
+                return new Iterator<T>()
+                {
+                    @Override
+                    public boolean hasNext()
+                    {
+                        return foundEntities.hasNext();
+                    }
+
+                    @Override
+                    public T next()
+                    {
+                        final EntityReference foundEntity = foundEntities.next();
+                        try
+                        {
+                            return moduleUnitOfWork.get( resultType, foundEntity.identity() );
+                        }
+                        catch( NoSuchEntityException e )
+                        {
+                            // Index is out of sync - entity has been removed
+                            return null;
+                        }
+                    }
+
+                    @Override
+                    public void remove()
+                    {
+                        throw new UnsupportedOperationException();
+                    }
+                };
+            }
+            catch( EntityFinderException e )
+            {
+                throw new QueryExecutionException( "Query '" + toString() + "' could not be executed", e );
+            }
+        }
+
+        @Override
+        public String toString()
+        {
+            return "UnitOfWork( " + moduleUnitOfWork.usecase().name() + " )";
+        }
+    }
+
+    private class ToValuePropertyMappingFunction
+        implements Function<PropertyDescriptor, Object>
+    {
+        private Object entity;
+
+        public ToValuePropertyMappingFunction( Object entity )
+        {
+            this.entity = entity;
+        }
+
+        @Override
+        public Object apply( PropertyDescriptor propertyDescriptor )
+        {
+            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
+            return entityState.propertyValueOf( propertyDescriptor.qualifiedName() );
+        }
+    }
+
+    private class ToValueAssociationMappingFunction<T>
+        implements Function<AssociationDescriptor, EntityReference>
+    {
+        private final T entity;
+
+        public ToValueAssociationMappingFunction( T entity )
+        {
+            this.entity = entity;
+        }
+
+        @Override
+        public EntityReference apply( AssociationDescriptor associationDescriptor )
+        {
+            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
+            return entityState.associationValueOf( associationDescriptor.qualifiedName() );
+        }
+    }
+
+    private class ToValueManyAssociationMappingFunction<T>
+        implements Function<AssociationDescriptor, Iterable<EntityReference>>
+    {
+        private final T entity;
+
+        public ToValueManyAssociationMappingFunction( T entity )
+        {
+            this.entity = entity;
+        }
+
+        @Override
+        public Iterable<EntityReference> apply( AssociationDescriptor associationDescriptor )
+        {
+            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
+            return entityState.manyAssociationValueOf( associationDescriptor.qualifiedName() );
+        }
+    }
+
+    private class ToValueNameAssociationMappingFunction<T>
+        implements Function<AssociationDescriptor, Map<String, EntityReference>>
+    {
+        private final T entity;
+
+        public ToValueNameAssociationMappingFunction( T entity )
+        {
+            this.entity = entity;
+        }
+
+        @Override
+        public Map<String, EntityReference> apply( AssociationDescriptor associationDescriptor )
+        {
+            Map<String, EntityReference> result = new HashMap<>();
+            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
+            final NamedAssociationState state = entityState.namedAssociationValueOf( associationDescriptor.qualifiedName() );
+            for( String name : state )
+            {
+                result.put( name, state.get( name ) );
+            }
+            return result;
+        }
+    }
+
+    private class ToEntityPropertyMappingFunction<T>
+        implements Function<PropertyDescriptor, Object>
+    {
+        private final T value;
+
+        public ToEntityPropertyMappingFunction( T value )
+        {
+            this.value = value;
+        }
+
+        @Override
+        public Object apply( PropertyDescriptor propertyDescriptor )
+        {
+            StateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
+            Property<Object> property = state.propertyFor( propertyDescriptor.accessor() );
+            return property.get();
+        }
+    }
+
+    private class ToEntityAssociationMappingFunction<T>
+        implements Function<AssociationDescriptor, EntityReference>
+    {
+
+        private final T value;
+
+        public ToEntityAssociationMappingFunction( T value )
+        {
+            this.value = value;
+        }
+
+        @Override
+        public EntityReference apply( AssociationDescriptor associationDescriptor )
+        {
+            AssociationStateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
+            AssociationInstance<T> association = (AssociationInstance<T>) state.associationFor( associationDescriptor.accessor() );
+            return association.getAssociationState().get();
+        }
+    }
+
+    private class ToEntityManyAssociationMappingFunction<T>
+        implements Function<AssociationDescriptor, Iterable<EntityReference>>
+    {
+
+        private final T value;
+
+        public ToEntityManyAssociationMappingFunction( T valueComposite )
+        {
+            this.value = valueComposite;
+        }
+
+        @Override
+        public Iterable<EntityReference> apply( AssociationDescriptor associationDescriptor )
+        {
+            AssociationStateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
+            ManyAssociationInstance<T> association =
+                (ManyAssociationInstance<T>) state.manyAssociationFor( associationDescriptor.accessor() );
+            return association.getManyAssociationState();
+        }
+    }
+
+    private class ToEntityNameAssociationMappingFunction<T>
+        implements Function<AssociationDescriptor, Map<String, EntityReference>>
+    {
+        private final T value;
+
+        public ToEntityNameAssociationMappingFunction( T valueComposite )
+        {
+            this.value = valueComposite;
+        }
+
+        @Override
+        public Map<String, EntityReference> apply( AssociationDescriptor associationDescriptor )
+        {
+            AssociationStateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
+            NamedAssociationInstance<T> association =
+                (NamedAssociationInstance<T>) state.namedAssociationFor( associationDescriptor.accessor() );
+            HashMap<String, EntityReference> result = new HashMap<>();
+            for( Map.Entry<String, EntityReference> entry : association.getEntityReferences() )
+            {
+                result.put( entry.getKey(), entry.getValue() );
+            }
+            return result;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryMixin.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryMixin.java b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryMixin.java
new file mode 100644
index 0000000..3a69e29
--- /dev/null
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryMixin.java
@@ -0,0 +1,100 @@
+/*
+ * 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.zest.runtime.unitofwork;
+
+import java.util.Stack;
+import org.apache.zest.api.common.Optional;
+import org.apache.zest.api.composite.TransientBuilderFactory;
+import org.apache.zest.api.entity.EntityComposite;
+import org.apache.zest.api.injection.scope.Structure;
+import org.apache.zest.api.injection.scope.Uses;
+import org.apache.zest.api.metrics.MetricsProvider;
+import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.api.usecase.Usecase;
+import org.apache.zest.runtime.entity.EntityInstance;
+import org.apache.zest.spi.module.ModuleSpi;
+
+public class UnitOfWorkFactoryMixin
+    implements UnitOfWorkFactory
+{
+    @Structure
+    private TransientBuilderFactory tbf;
+
+    @Structure
+    private ModuleSpi module;
+
+    // Implementation of UnitOfWorkFactory
+    @Override
+    public UnitOfWork newUnitOfWork()
+    {
+        return newUnitOfWork( Usecase.DEFAULT );
+    }
+
+    @Override
+    public UnitOfWork newUnitOfWork( long currentTime )
+    {
+        return newUnitOfWork( Usecase.DEFAULT, currentTime );
+    }
+
+    @Override
+    public UnitOfWork newUnitOfWork( Usecase usecase )
+    {
+        return newUnitOfWork( usecase == null ? Usecase.DEFAULT : usecase, System.currentTimeMillis() );
+    }
+
+    @Override
+    public UnitOfWork newUnitOfWork( Usecase usecase, long currentTime )
+    {
+        UnitOfWorkInstance unitOfWorkInstance = new UnitOfWorkInstance( usecase, currentTime, metricsProvider() );
+        return tbf.newTransient( UnitOfWork.class, unitOfWorkInstance );
+    }
+
+    private MetricsProvider metricsProvider()
+    {
+        return module.metricsProvider();
+    }
+
+    @Override
+    public boolean isUnitOfWorkActive()
+    {
+        Stack<UnitOfWorkInstance> stack = UnitOfWorkInstance.getCurrent();
+        return !stack.isEmpty();
+    }
+
+    @Override
+    public UnitOfWork currentUnitOfWork()
+    {
+        Stack<UnitOfWorkInstance> stack = UnitOfWorkInstance.getCurrent();
+        if( stack.size() == 0 )
+        {
+            throw new IllegalStateException( "No current UnitOfWork active" );
+        }
+        return tbf.newTransient( UnitOfWork.class, stack.peek() );
+    }
+
+    @Override
+    public UnitOfWork getUnitOfWork( EntityComposite entity )
+    {
+        EntityInstance instance = EntityInstance.entityInstanceOf( entity );
+        return instance.unitOfWork();
+    }
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkInstance.java
index fc0810b..3a65c9f 100755
--- a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/UnitOfWorkInstance.java
@@ -1,20 +1,23 @@
 /*
- * Copyright (c) 2007-2013, Niclas Hedhman. All Rights Reserved.
+ * 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
  *
- * Licensed 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
  *
- * 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.
  *
- * 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.zest.runtime.unitofwork;
 
 import java.util.ArrayList;
@@ -37,6 +40,7 @@ import org.apache.zest.api.type.HasTypes;
 import org.apache.zest.api.unitofwork.ConcurrentEntityModificationException;
 import org.apache.zest.api.unitofwork.EntityTypeNotFoundException;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
+import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCallback;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
 import org.apache.zest.api.unitofwork.UnitOfWorkException;
@@ -44,7 +48,6 @@ import org.apache.zest.api.unitofwork.UnitOfWorkOptions;
 import org.apache.zest.api.usecase.Usecase;
 import org.apache.zest.runtime.entity.EntityInstance;
 import org.apache.zest.runtime.entity.EntityModel;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
 import org.apache.zest.spi.entity.EntityState;
 import org.apache.zest.spi.entity.EntityStatus;
 import org.apache.zest.spi.entitystore.ConcurrentEntityStateModificationException;
@@ -53,8 +56,8 @@ import org.apache.zest.spi.entitystore.EntityStore;
 import org.apache.zest.spi.entitystore.EntityStoreUnitOfWork;
 import org.apache.zest.spi.entitystore.StateCommitter;
 import org.apache.zest.spi.metrics.DefaultMetric;
-import org.apache.zest.spi.module.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
+import org.apache.zest.spi.structure.ModelModule;
 
 import static org.apache.zest.api.unitofwork.UnitOfWorkCallback.UnitOfWorkStatus.COMPLETED;
 import static org.apache.zest.api.unitofwork.UnitOfWorkCallback.UnitOfWorkStatus.DISCARDED;
@@ -123,7 +126,7 @@ public final class UnitOfWorkInstance
     }
 
     public <T> T get( EntityReference identity,
-                      ModuleUnitOfWork uow,
+                      UnitOfWork uow,
                       Iterable<ModelModule<EntityDescriptor>> potentialModels,
                       Class<T> mixinType
     )
@@ -175,10 +178,8 @@ public final class UnitOfWorkInstance
                     );
                 }
             }
-
             // Create instance
             entityInstance = new EntityInstance( uow, module, model, entityState );
-
             instanceCache.put( identity, entityInstance );
         }
         else
@@ -390,10 +391,7 @@ public final class UnitOfWorkInstance
         // Notify explicitly registered callbacks
         if( callbacks != null )
         {
-            for( UnitOfWorkCallback callback : callbacks )
-            {
-                callback.beforeCompletion();
-            }
+            callbacks.forEach( UnitOfWorkCallback::beforeCompletion );
         }
 
         // Notify entities

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderInstance.java
index 9f72fe2..45e9282 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderInstance.java
@@ -21,7 +21,7 @@ import org.apache.zest.api.value.ValueBuilder;
 import org.apache.zest.api.value.ValueDescriptor;
 import org.apache.zest.runtime.composite.StateResolver;
 import org.apache.zest.runtime.structure.ModuleInstance;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 
 /**
  * Implementation of ValueBuilder

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithPrototype.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithPrototype.java b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithPrototype.java
index a878ab2..eafd07a 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithPrototype.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithPrototype.java
@@ -38,7 +38,7 @@ import org.apache.zest.runtime.composite.MixinsModel;
 import org.apache.zest.runtime.composite.StateResolver;
 import org.apache.zest.runtime.composite.UsesInstance;
 import org.apache.zest.runtime.injection.InjectionContext;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.runtime.structure.ModuleInstance;
 
 /**

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithState.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithState.java b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithState.java
index db97002..69c06c4 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithState.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueBuilderWithState.java
@@ -18,7 +18,7 @@ import org.apache.zest.api.common.ConstructionException;
 import org.apache.zest.api.value.ValueBuilder;
 import org.apache.zest.api.value.ValueDescriptor;
 import org.apache.zest.runtime.composite.StateResolver;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.runtime.structure.ModuleInstance;
 
 public class ValueBuilderWithState<T> implements ValueBuilder<T>

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueStateInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueStateInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueStateInstance.java
index ed0083b..313567e 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueStateInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/value/ValueStateInstance.java
@@ -35,7 +35,8 @@ import org.apache.zest.runtime.composite.StateResolver;
 import org.apache.zest.runtime.property.PropertyInfo;
 import org.apache.zest.runtime.property.PropertyInstance;
 import org.apache.zest.runtime.structure.ModuleInstance;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.runtime.unitofwork.EntityFunction;
+import org.apache.zest.spi.structure.ModelModule;
 
 /**
  * TODO
@@ -65,6 +66,8 @@ public final class ValueStateInstance
                                StateResolver stateResolver
     )
     {
+        EntityFunction entityFunction = new EntityFunction( currentModule.unitOfWorkFactory() );
+
         ValueModel valueModel = (ValueModel) compositeModelModule.model();
         this.properties = new LinkedHashMap<>();
         valueModel.state().properties().forEach( propertyDescriptor -> {
@@ -80,7 +83,7 @@ public final class ValueStateInstance
             EntityReference value = stateResolver.getAssociationState( associationDescriptor );
             AssociationInstance<Object> associationInstance1 = new AssociationInstance<>(
                 builderInfo,
-                currentModule.getEntityFunction(),
+                entityFunction,
                 new ReferenceProperty( value ) );
             associations.put( associationDescriptor.accessor(), associationInstance1 );
         } );
@@ -93,7 +96,7 @@ public final class ValueStateInstance
             ManyAssociationValueState manyAssociationState = new ManyAssociationValueState( value );
             ManyAssociationInstance<Object> associationInstance = new ManyAssociationInstance<>(
                 builderInfo,
-                currentModule.getEntityFunction(),
+                entityFunction,
                 manyAssociationState );
             manyAssociations.put( associationDescriptor.accessor(), associationInstance );
         } );
@@ -106,7 +109,7 @@ public final class ValueStateInstance
             NamedAssociationValueState namedAssociationState = new NamedAssociationValueState( value );
             NamedAssociationInstance<Object> associationInstance = new NamedAssociationInstance<>(
                 builderInfo,
-                currentModule.getEntityFunction(),
+                entityFunction,
                 namedAssociationState );
             namedAssociations.put( associationDescriptor.accessor(), associationInstance );
         } );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/api/common/OptionalTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/api/common/OptionalTest.java b/core/runtime/src/test/java/org/apache/zest/api/common/OptionalTest.java
index 355ee8e..ed1b8c3 100644
--- a/core/runtime/src/test/java/org/apache/zest/api/common/OptionalTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/api/common/OptionalTest.java
@@ -95,7 +95,7 @@ public class OptionalTest
     public void givenOptionalAssociationWhenOptionalMissingThenNoException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             TestComposite4 ref = unitOfWork.newEntity( TestComposite4.class );
@@ -116,7 +116,7 @@ public class OptionalTest
     public void givenOptionalAssociationWhenOptionalSetThenNoException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             TestComposite4 ref = unitOfWork.newEntity( TestComposite4.class );
@@ -138,7 +138,7 @@ public class OptionalTest
     public void givenMandatoryAssociationWhenMandatoryMissingThenException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             TestComposite4 ref = unitOfWork.newEntity( TestComposite4.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/api/common/PropertyErrorTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/api/common/PropertyErrorTest.java b/core/runtime/src/test/java/org/apache/zest/api/common/PropertyErrorTest.java
index 1201329..6add3eb 100644
--- a/core/runtime/src/test/java/org/apache/zest/api/common/PropertyErrorTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/api/common/PropertyErrorTest.java
@@ -41,7 +41,7 @@ public class PropertyErrorTest
     public void givenEntityWithNonOptionPropertyWhenInstantiatedThenException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             PersonEntity person = unitOfWork.newEntity( PersonEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/api/common/PropertyTypeTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/api/common/PropertyTypeTest.java b/core/runtime/src/test/java/org/apache/zest/api/common/PropertyTypeTest.java
index 4bcc88a..e3f5a7e 100644
--- a/core/runtime/src/test/java/org/apache/zest/api/common/PropertyTypeTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/api/common/PropertyTypeTest.java
@@ -49,7 +49,7 @@ public class PropertyTypeTest
     public void givenEntityWithPropertyConstraintsWhenInstantiatedThenPropertiesWork()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder( PersonEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/api/common/RemovalTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/api/common/RemovalTest.java b/core/runtime/src/test/java/org/apache/zest/api/common/RemovalTest.java
index 76b80bf..8b33ac0 100644
--- a/core/runtime/src/test/java/org/apache/zest/api/common/RemovalTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/api/common/RemovalTest.java
@@ -44,7 +44,7 @@ public class RemovalTest
     public void givenEntityIsCreatedAndUnitOfWorkIsNotCompletedWhenEntityIsRemoveThenSuccessfulRemoval()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         EntityBuilder<TestEntity> builder = uow.newEntityBuilder( TestEntity.class, "123" );
         builder.instance().test().set( "habba" );
         TestEntity test = builder.newInstance();
@@ -56,7 +56,7 @@ public class RemovalTest
     public void givenStandardPidRegulatorWhenNoChangeInInputExpectOutputToGoTowardsMinimum()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         PidRegulator regulator = null;
         try
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/api/common/ValueCompositeTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/api/common/ValueCompositeTest.java b/core/runtime/src/test/java/org/apache/zest/api/common/ValueCompositeTest.java
index 77d1a96..42360ad 100644
--- a/core/runtime/src/test/java/org/apache/zest/api/common/ValueCompositeTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/api/common/ValueCompositeTest.java
@@ -183,7 +183,7 @@ public class ValueCompositeTest
         builder.prototype().number().set( 42L );
         SomeValue some = builder.newInstance();
 
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         EntityBuilder<SomeEntity> entityBuilder = unitOfWork.newEntityBuilder( SomeEntity.class );
         entityBuilder.instance().someValue().set( some );
         SomeEntity entity = entityBuilder.newInstance();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/regression/qi377/InterfaceCollisionWithRelatedReturnTypesTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/regression/qi377/InterfaceCollisionWithRelatedReturnTypesTest.java b/core/runtime/src/test/java/org/apache/zest/regression/qi377/InterfaceCollisionWithRelatedReturnTypesTest.java
index 0524c64..4688883 100644
--- a/core/runtime/src/test/java/org/apache/zest/regression/qi377/InterfaceCollisionWithRelatedReturnTypesTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/regression/qi377/InterfaceCollisionWithRelatedReturnTypesTest.java
@@ -52,14 +52,14 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
         throws UnitOfWorkCompletionException
     {
         String identity;
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             Company startUp = uow.newEntity( Company.class );
             startUp.name().set( "Acme" );
             identity = ( (Identity) startUp ).identity().get();
             uow.complete();
         }
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             Company startUp = uow.get( Company.class, identity );
             assertThat( startUp.name().get(), equalTo( "Acme" ) );
@@ -77,7 +77,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
         throws UnitOfWorkCompletionException
     {
         String identity;
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             Company startUp = uow.newEntity( Company.class );
             Employee niclas = uow.newEntity( Employee.class );
@@ -87,7 +87,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
 
             uow.complete();
         }
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             Company startUp = uow.get( Company.class, identity );
             Employee niclas = startUp.lead().get();
@@ -104,7 +104,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
     @Test
     public void shouldBeAbleToSetLeadToTheSalesTeam()
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             SalesTeam startUp = uow.newEntity( SalesTeam.class );
             Employee niclas = uow.newEntity( Employee.class );
@@ -116,7 +116,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
     @Test
     public void shouldBeAbleToSetLeadToTheResearchTeam()
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             ResearchTeam startUp = uow.newEntity( ResearchTeam.class );
             Employee niclas = uow.newEntity( Employee.class );
@@ -128,7 +128,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
     @Test
     public void shouldBeAbleToAddEmployeesToTheCompany()
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             Company startUp = uow.newEntity( Company.class );
             Employee niclas = uow.newEntity( Employee.class );
@@ -142,7 +142,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
     @Test
     public void shouldBeAbleToAddEmployeesToTheSalesTeam()
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             SalesTeam startUp = uow.newEntity( SalesTeam.class );
             Employee niclas = uow.newEntity( Employee.class );
@@ -154,7 +154,7 @@ public class InterfaceCollisionWithRelatedReturnTypesTest
     @Test
     public void shouldBeAbleToAddEmployeesToTheResearchTeam()
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             ResearchTeam startUp = uow.newEntity( ResearchTeam.class );
             Employee niclas = uow.newEntity( Employee.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/regression/qi377/SetAssociationInSideEffectTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/regression/qi377/SetAssociationInSideEffectTest.java b/core/runtime/src/test/java/org/apache/zest/regression/qi377/SetAssociationInSideEffectTest.java
index a2933be..7564016 100644
--- a/core/runtime/src/test/java/org/apache/zest/regression/qi377/SetAssociationInSideEffectTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/regression/qi377/SetAssociationInSideEffectTest.java
@@ -56,7 +56,7 @@ public class SetAssociationInSideEffectTest
     @Test
     public void whenSettingAnAssociationInASideEffectExpectItToWork()
     {
-        try( UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Purchase Steinway" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Purchase Steinway" ) ) )
         {
             Pianist chris = uow.newEntity( Pianist.class, "Chris" );
             Steinway modelD = uow.newEntity( Steinway.class, "ModelD-274" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/regression/qi382/Qi382Test.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/regression/qi382/Qi382Test.java b/core/runtime/src/test/java/org/apache/zest/regression/qi382/Qi382Test.java
index ea2ebc1..ca655f8 100644
--- a/core/runtime/src/test/java/org/apache/zest/regression/qi382/Qi382Test.java
+++ b/core/runtime/src/test/java/org/apache/zest/regression/qi382/Qi382Test.java
@@ -17,6 +17,7 @@
  */
 package org.apache.zest.regression.qi382;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Test;
 import org.apache.zest.api.association.Association;
 import org.apache.zest.api.entity.EntityBuilder;
@@ -26,7 +27,6 @@ import org.apache.zest.api.entity.LifecycleException;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.mixin.Mixins;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
 import org.apache.zest.api.value.ValueSerialization;
@@ -56,12 +56,12 @@ public class Qi382Test extends AbstractZestTest
     public void givenCreationOfTwoEntitiesWhenAssigningOneToOtherExpectCompletionToSucceed()
         throws UnitOfWorkCompletionException
     {
-        try( UnitOfWork unitOfWork = module.newUnitOfWork() )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork() )
         {
             Car car = unitOfWork.newEntity( Car.class, "Ferrari" );
             unitOfWork.complete();
         }
-        try( UnitOfWork unitOfWork = module.newUnitOfWork() )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork() )
         {
             Car car = unitOfWork.get( Car.class, "Ferrari" );
             assertThat( car, notNullValue() );
@@ -81,13 +81,13 @@ public class Qi382Test extends AbstractZestTest
             private Car me;
 
             @Structure
-            private Module module;
+            private UnitOfWorkFactory uowf;
 
             @Override
             public void create()
                 throws LifecycleException
             {
-                UnitOfWork unitOfWork = module.currentUnitOfWork();
+                UnitOfWork unitOfWork = uowf.currentUnitOfWork();
                 EntityBuilder<Person> builder = unitOfWork.newEntityBuilder( Person.class, "Niclas" );
                 builder.instance().car().set( me );
                 builder.newInstance();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/regression/qi383/Qi383Test.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/regression/qi383/Qi383Test.java b/core/runtime/src/test/java/org/apache/zest/regression/qi383/Qi383Test.java
index c4461cb..f3bcd2f 100644
--- a/core/runtime/src/test/java/org/apache/zest/regression/qi383/Qi383Test.java
+++ b/core/runtime/src/test/java/org/apache/zest/regression/qi383/Qi383Test.java
@@ -44,7 +44,7 @@ public class Qi383Test extends AbstractZestTest
     public void givenUnitOfWorkInProgressWhenAddingSameEntityTwiceExpectException()
         throws UnitOfWorkCompletionException
     {
-        try( UnitOfWork unitOfWork = module.newUnitOfWork() )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork() )
         {
             unitOfWork.newEntity( Car.class, "Ferrari" );
             unitOfWork.newEntity( Car.class, "Ford" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/regression/qi59/IssueTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/regression/qi59/IssueTest.java b/core/runtime/src/test/java/org/apache/zest/regression/qi59/IssueTest.java
index 0363137..29baada 100644
--- a/core/runtime/src/test/java/org/apache/zest/regression/qi59/IssueTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/regression/qi59/IssueTest.java
@@ -42,7 +42,7 @@ public class IssueTest
     @Test
     public void givenEntityWithConstrainedPropertyWhenInvalidPropertyValueSetThenThrowException()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         try
         {
@@ -62,7 +62,7 @@ public class IssueTest
     @Test
     public void givenEntityWithComplexConstrainedPropertyWhenInvalidPropertyValueSetThenThrowException()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         try
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/regression/qi94/IssueTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/regression/qi94/IssueTest.java b/core/runtime/src/test/java/org/apache/zest/regression/qi94/IssueTest.java
index d799ddc..18bc396 100644
--- a/core/runtime/src/test/java/org/apache/zest/regression/qi94/IssueTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/regression/qi94/IssueTest.java
@@ -44,7 +44,7 @@ public class IssueTest
     @Test
     public void entityBuilderAssociationTypeIsNotNull()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Item> builder = uow.newEntityBuilder( Item.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/ZestAPITest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/ZestAPITest.java b/core/runtime/src/test/java/org/apache/zest/runtime/ZestAPITest.java
index df40a4d..a9f7dfa 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/ZestAPITest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/ZestAPITest.java
@@ -45,7 +45,7 @@ public class ZestAPITest
     public void testGetModuleOfComposite()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         TestEntity testEntity = unitOfWork.newEntity( TestEntity.class );
 
         api.moduleOf( testEntity );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/ZestSPITest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/ZestSPITest.java b/core/runtime/src/test/java/org/apache/zest/runtime/ZestSPITest.java
index d171396..76f2433 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/ZestSPITest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/ZestSPITest.java
@@ -53,7 +53,7 @@ public class ZestSPITest
     public void givenEntityWhenGettingStateThenGetCorrectState()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         TestEntity testEntity;
         try
         {
@@ -72,7 +72,7 @@ public class ZestSPITest
             unitOfWork.discard();
         }
 
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             testEntity = uow.get( testEntity );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/appliesto/AppliesToOrConditionQI241Test.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/appliesto/AppliesToOrConditionQI241Test.java b/core/runtime/src/test/java/org/apache/zest/runtime/appliesto/AppliesToOrConditionQI241Test.java
index 7054b37..f2ec635 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/appliesto/AppliesToOrConditionQI241Test.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/appliesto/AppliesToOrConditionQI241Test.java
@@ -57,7 +57,7 @@ public class AppliesToOrConditionQI241Test
     @Test
     public void testMultiConcerns1()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         try
         {
@@ -76,7 +76,7 @@ public class AppliesToOrConditionQI241Test
     @Test
     public void testMultiConcerns2()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         try
         {
@@ -95,7 +95,7 @@ public class AppliesToOrConditionQI241Test
     @Test
     public void testMultiConcernsBoth()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         try
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationAssignmentTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationAssignmentTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationAssignmentTest.java
index d0c7147..8e9f338 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationAssignmentTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationAssignmentTest.java
@@ -56,7 +56,7 @@ public class AssociationAssignmentTest extends AbstractZestTest
     public void givenAssignmentOfAssociationAtCreationWhenDereferencingAssocationExpectCorrectValue()
         throws Exception
     {
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         TheAssociatedType entity1 = work.newEntity( TheAssociatedType.class );
         EntityBuilder<TheMainType> builder = work.newEntityBuilder( TheMainType.class );
         builder.instance().assoc().set( entity1 );
@@ -67,7 +67,7 @@ public class AssociationAssignmentTest extends AbstractZestTest
         assertThat(id1, notNullValue());
         assertThat(id2, notNullValue());
 
-        work = module.newUnitOfWork();
+        work = uowf.newUnitOfWork();
         TheMainType entity3 = work.get(TheMainType.class, id2 );
         TheAssociatedType entity4 = entity3.assoc().get();
         assertThat( entity4.identity().get(), equalTo(id1));

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationEqualityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationEqualityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationEqualityTest.java
index ab5222f..4ffc14b 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationEqualityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/association/AssociationEqualityTest.java
@@ -84,7 +84,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfTheSameTypeAndSameStateWhenTestingAssociationDescriptorEqualityExpectEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             AnEntity anEntity = uow.newEntity( AnEntity.class );
@@ -127,7 +127,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfTheSameTypeAndDifferentStateWhenTestingAssociationDescriptorEqualityExpectEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             SomeWithAssociations some = buildSomeWithAssociation( uow.newEntity( AnEntity.class ) );
@@ -168,7 +168,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfDifferentTypeAndSameStateWhenTestingAssociationDescriptorEqualityExpectNotEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             AnEntity anEntity = uow.newEntity( AnEntity.class );
@@ -214,7 +214,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfSameTypeAndDifferentStateWhenTestingAssociationStateEqualityExpectNotEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             SomeWithAssociations some = buildSomeWithAssociation( uow.newEntity( AnEntity.class ) );
@@ -248,7 +248,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfDifferentTypesAndSameStateWhenTestingAssociationStateEqualityExpectEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             AnEntity anEntity = uow.newEntity( AnEntity.class );
@@ -287,7 +287,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfTheSameTypeAndSameStateWhenTestingAssociationEqualityExpectEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             AnEntity anEntity = uow.newEntity( AnEntity.class );
@@ -323,7 +323,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfTheSameTypeAndDifferentStateWhenTestingAssociationEqualityExpectNotEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             SomeWithAssociations some = buildSomeWithAssociation( uow.newEntity( AnEntity.class ) );
@@ -357,7 +357,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfDifferentTypesAndSameStateWhenTestingAssociationEqualityExpectNotEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             AnEntity anEntity = uow.newEntity( AnEntity.class );
@@ -393,7 +393,7 @@ public class AssociationEqualityTest
     @Test
     public void givenValuesOfDifferentTypesAndDifferentStateWhenTestingAssociationEqualityExpectNotEquals()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             SomeWithAssociations some = buildSomeWithAssociation( uow.newEntity( AnEntity.class ) );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientAsClassTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientAsClassTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientAsClassTest.java
index 226dd47..5d7839b 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientAsClassTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientAsClassTest.java
@@ -18,6 +18,10 @@
  */
 package org.apache.zest.runtime.composite;
 
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import org.apache.zest.api.concern.ConcernOf;
+import org.apache.zest.api.concern.Concerns;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.apache.zest.bootstrap.AssemblyException;
@@ -30,15 +34,27 @@ import static org.junit.Assert.assertThat;
 /**
  * Test for QI-298.
  */
-@Ignore( "Awaiting QI-298" )
 public class TransientAsClassTest
     extends AbstractZestTest
 {
+    public static class UnderTestConcern extends ConcernOf<InvocationHandler>
+        implements InvocationHandler
+    {
+
+        @Override
+        public Object invoke( Object proxy, Method method, Object[] args )
+            throws Throwable
+        {
+            return next.invoke( proxy, method, args ) + " bar";
+        }
+    }
+
+    @Concerns(UnderTestConcern.class)
     public static class UnderTest
     {
         public String foo()
         {
-            return "bar";
+            return "foo";
         }
     }
 
@@ -53,6 +69,6 @@ public class TransientAsClassTest
     public void test()
     {
         UnderTest underTest = module.newTransient( UnderTest.class );
-        assertThat( underTest.foo(), equalTo( "bar" ) );
+        assertThat( underTest.foo(), equalTo( "foo bar" ) );
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientClassLoaderTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientClassLoaderTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientClassLoaderTest.java
new file mode 100644
index 0000000..56808b3
--- /dev/null
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/composite/TransientClassLoaderTest.java
@@ -0,0 +1,30 @@
+/*
+ * 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.zest.runtime.composite;
+
+public class TransientClassLoaderTest
+{
+
+    public void givenTransientWhenLoadingClassExpectSubclassGenerated()
+    {
+//        new TransientClassLoader( getClass().getClassLoader() ).loadFragmentClass( mainType );
+    }
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/concerns/GenericConcernTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/concerns/GenericConcernTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/concerns/GenericConcernTest.java
index 9a951d9..d243c64 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/concerns/GenericConcernTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/concerns/GenericConcernTest.java
@@ -42,7 +42,7 @@ public class GenericConcernTest
     @Test
     public void testNestedUnitOfWork()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         Some some = module.newTransient( Some.class );
         some.doStuff();
         uow.discard();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/AggregatedTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/AggregatedTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/AggregatedTest.java
index 58bacd2..abf5c66 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/AggregatedTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/AggregatedTest.java
@@ -54,7 +54,7 @@ public class AggregatedTest
         CompanyEntity companyEntity;
         PersonEntity personEntity, personEntity2;
         EmployeeEntity employeeEntity, employeeEntity2;
-        try( UnitOfWork unitOfWork = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Creation" ) ) )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Creation" ) ) )
         {
             {
                 EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder( PersonEntity.class );
@@ -100,7 +100,7 @@ public class AggregatedTest
             unitOfWork.complete();
         }
 
-        try( UnitOfWork unitOfWork = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Removal" ) ) )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Removal" ) ) )
         {
             companyEntity = unitOfWork.get( companyEntity );
             unitOfWork.remove( companyEntity );
@@ -108,7 +108,7 @@ public class AggregatedTest
             unitOfWork.complete();
         }
 
-        try( UnitOfWork unitOfWork = module.newUnitOfWork( UsecaseBuilder.newUsecase( "No 1st employee" ) ) )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "No 1st employee" ) ) )
         {
             unitOfWork.get( employeeEntity );
             fail( "Should not work" );
@@ -118,7 +118,7 @@ public class AggregatedTest
             // Expected
         }
 
-        try( UnitOfWork unitOfWork = module.newUnitOfWork( UsecaseBuilder.newUsecase( "No 2nd employee" ) ) )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "No 2nd employee" ) ) )
         {
             unitOfWork.get( employeeEntity2 );
             fail( "Should not work" );
@@ -128,7 +128,7 @@ public class AggregatedTest
             // Expected
         }
 
-        try( UnitOfWork unitOfWork = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Persons not removed" ) ) )
+        try( UnitOfWork unitOfWork = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Persons not removed" ) ) )
         {
             unitOfWork.get( personEntity );
             unitOfWork.get( personEntity2 );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityBuilderWithStateTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityBuilderWithStateTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityBuilderWithStateTest.java
index 2f23f8a..cd501d1 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityBuilderWithStateTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityBuilderWithStateTest.java
@@ -17,11 +17,9 @@ package org.apache.zest.runtime.entity;
 
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.Map;
-import java.util.function.Function;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Test;
 import org.apache.zest.api.association.Association;
-import org.apache.zest.api.association.AssociationDescriptor;
 import org.apache.zest.api.association.ManyAssociation;
 import org.apache.zest.api.association.NamedAssociation;
 import org.apache.zest.api.common.Optional;
@@ -29,7 +27,6 @@ import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.entity.EntityReference;
 import org.apache.zest.api.entity.Identity;
 import org.apache.zest.api.property.Property;
-import org.apache.zest.api.property.PropertyDescriptor;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
 import org.apache.zest.bootstrap.AssemblyException;
@@ -52,6 +49,7 @@ public class EntityBuilderWithStateTest
     {
         new EntityTestAssembler().assemble( module );
         module.entities( SomeEntity.class );
+        new DefaultUnitOfWorkAssembler().assemble( module );
     }
 
     @Test
@@ -59,7 +57,7 @@ public class EntityBuilderWithStateTest
         throws UnitOfWorkCompletionException
     {
         final String associatedIdentity;
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             EntityBuilder<SomeEntity> builder = uow.newEntityBuilder( SomeEntity.class );
             builder.instance().prop().set( "Associated" );
@@ -67,60 +65,40 @@ public class EntityBuilderWithStateTest
             associatedIdentity = entity.identity().get();
             uow.complete();
         }
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             SomeEntity entity = uow.newEntityBuilderWithState(
                 SomeEntity.class,
-                new Function<PropertyDescriptor, Object>()
-                {
-                    @Override
-                    public Object apply( PropertyDescriptor descriptor )
+                descriptor -> {
+                    if( "prop".equals( descriptor.qualifiedName().name() ) )
                     {
-                        if( "prop".equals( descriptor.qualifiedName().name() ) )
-                        {
-                            return "Foo";
-                        }
-                        return null;
+                        return "Foo";
                     }
+                    return null;
                 },
-                new Function<AssociationDescriptor, EntityReference>()
-                {
-                    @Override
-                    public EntityReference apply( AssociationDescriptor descriptor )
+                descriptor -> {
+                    if( "ass".equals( descriptor.qualifiedName().name() ) )
                     {
-                        if( "ass".equals( descriptor.qualifiedName().name() ) )
-                        {
-                            return EntityReference.parseEntityReference( associatedIdentity );
-                        }
-                        return null;
+                        return EntityReference.parseEntityReference( associatedIdentity );
                     }
+                    return null;
                 },
-                new Function<AssociationDescriptor, Iterable<EntityReference>>()
-                {
-                    @Override
-                    public Iterable<EntityReference> apply( AssociationDescriptor descriptor )
+                descriptor -> {
+                    if( "manyAss".equals( descriptor.qualifiedName().name() ) )
                     {
-                        if( "manyAss".equals( descriptor.qualifiedName().name() ) )
-                        {
-                            return Arrays.asList( EntityReference.parseEntityReference( associatedIdentity ) );
-                        }
-                        return null;
+                        return Arrays.asList( EntityReference.parseEntityReference( associatedIdentity ) );
                     }
+                    return null;
                 },
-                new Function<AssociationDescriptor, Map<String, EntityReference>>()
-                {
-                    @Override
-                    public Map<String, EntityReference> apply( AssociationDescriptor descriptor )
+                descriptor -> {
+                    if( "namedAss".equals( descriptor.qualifiedName().name() ) )
                     {
-                        if( "namedAss".equals( descriptor.qualifiedName().name() ) )
-                        {
-                            return Collections.singletonMap(
-                                "foo",
-                                EntityReference.parseEntityReference( associatedIdentity )
-                            );
-                        }
-                        return null;
+                        return Collections.singletonMap(
+                            "foo",
+                            EntityReference.parseEntityReference( associatedIdentity )
+                        );
                     }
+                    return null;
                 }
             ).newInstance();
             assertThat( entity.prop().get(), equalTo( "Foo" ) );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCompositeEqualityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCompositeEqualityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCompositeEqualityTest.java
index 980a3dd..f451f70 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCompositeEqualityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCompositeEqualityTest.java
@@ -49,7 +49,7 @@ public class EntityCompositeEqualityTest
         throws Exception
     {
         super.setUp();
-        unitOfWork = this.module.newUnitOfWork();
+        unitOfWork = this.uowf.newUnitOfWork();
         myCompositeBuilder = unitOfWork.newEntityBuilder( MyComposite.class );
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCreationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCreationTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCreationTest.java
index d514312..d4b7f43 100755
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCreationTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityCreationTest.java
@@ -79,7 +79,7 @@ public class EntityCreationTest
     @Test
     public void doTestUseUowNewEntity()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         SomeEntity entity = uow.newEntity( SomeEntity.class );
         uow.discard();
     }
@@ -87,7 +87,7 @@ public class EntityCreationTest
     @Test
     public void doTestUseEntityBuilder()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         EntityBuilder<SomeEntity> builder = uow.newEntityBuilder( SomeEntity.class );
         SomeEntity entity = builder.newInstance();
         uow.discard();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityTypeTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityTypeTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityTypeTest.java
index 2c15fdc..4a7c1d8 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityTypeTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityTypeTest.java
@@ -34,7 +34,7 @@ public class EntityTypeTest
     public void givenSubclassedEntityWhenRequestingSuperclassExpectResolutionToWork()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Rst> builder3 = uow.newEntityBuilder( Rst.class, "123" );


[4/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi95/Qi95IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi95/Qi95IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi95/Qi95IssueTest.java
index bb7f78f..b67db87 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi95/Qi95IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi95/Qi95IssueTest.java
@@ -21,6 +21,7 @@ import java.io.File;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Rule;
 import org.junit.Test;
 import org.apache.zest.api.common.Visibility;
@@ -61,7 +62,7 @@ public class Qi95IssueTest
         {
             application.activate();
             Module domain = application.findModule( "Domain", "Domain" );
-            UnitOfWorkFactory unitOfWorkFactory = domain;
+            UnitOfWorkFactory unitOfWorkFactory = domain.unitOfWorkFactory();
             createABunchOfStuffAndDoQueries( unitOfWorkFactory, domain );
         }
         finally
@@ -79,7 +80,7 @@ public class Qi95IssueTest
         {
             application.activate();
             Module domain = application.findModule( "Domain", "Domain" );
-            UnitOfWorkFactory unitOfWorkFactory = domain;
+            UnitOfWorkFactory unitOfWorkFactory = domain.unitOfWorkFactory();
             createABunchOfStuffAndDoQueries( unitOfWorkFactory, domain );
         }
         finally
@@ -97,7 +98,7 @@ public class Qi95IssueTest
         {
             application.activate();
             Module domain = application.findModule( "Domain", "Domain" );
-            UnitOfWorkFactory unitOfWorkFactory = domain;
+            UnitOfWorkFactory unitOfWorkFactory = domain.unitOfWorkFactory();
             createABunchOfStuffAndDoQueries( unitOfWorkFactory, domain );
         }
         finally
@@ -116,7 +117,7 @@ public class Qi95IssueTest
             application.activate();
 
             Module domain = application.findModule( "Domain", "Domain" );
-            UnitOfWorkFactory unitOfWorkFactory = domain;
+            UnitOfWorkFactory unitOfWorkFactory = domain.unitOfWorkFactory();
             createABunchOfStuffAndDoQueries( unitOfWorkFactory, domain );
         }
         finally
@@ -278,6 +279,7 @@ public class Qi95IssueTest
                     throws AssemblyException
                 {
                     module.entities( ItemTypeEntity.class );
+                    new DefaultUnitOfWorkAssembler().assemble( module );
                 }
             } );
             return domainLayer;
@@ -293,6 +295,7 @@ public class Qi95IssueTest
                 throws AssemblyException
             {
                 new EntityTestAssembler().assemble( module );
+                new DefaultUnitOfWorkAssembler().assemble( module );
 
                 module.entities( NativeConfiguration.class ).visibleIn( Visibility.application );
                 module.forMixin( NativeConfiguration.class )
@@ -320,6 +323,7 @@ public class Qi95IssueTest
             {
                 new OrgJsonValueSerializationAssembler().assemble( module );
                 new JdbmEntityStoreAssembler().visibleIn( Visibility.application ).assemble( module );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
     }
@@ -329,6 +333,7 @@ public class Qi95IssueTest
     {
         ModuleAssembly moduleAssembly = layerAssembly.module( name );
         assembler.assemble( moduleAssembly );
+        new DefaultUnitOfWorkAssembler().assemble( moduleAssembly );
         return moduleAssembly;
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-solr/src/test/java/org/apache/zest/index/solr/SolrQueryServiceTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/test/java/org/apache/zest/index/solr/SolrQueryServiceTest.java b/extensions/indexing-solr/src/test/java/org/apache/zest/index/solr/SolrQueryServiceTest.java
index 29509ea..621b02f 100644
--- a/extensions/indexing-solr/src/test/java/org/apache/zest/index/solr/SolrQueryServiceTest.java
+++ b/extensions/indexing-solr/src/test/java/org/apache/zest/index/solr/SolrQueryServiceTest.java
@@ -73,7 +73,7 @@ public class SolrQueryServiceTest
         throws UnitOfWorkCompletionException, InterruptedException
     {
         // Create and index an entity
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         TestEntity test = uow.newEntity( TestEntity.class );
         test.name().set( "Hello World" );
         uow.complete();
@@ -85,7 +85,7 @@ public class SolrQueryServiceTest
         throws UnitOfWorkCompletionException
     {
         // Search for it
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         Query<TestEntity> query = uow.newQuery( module.newQueryBuilder( TestEntity.class ).where( SolrExpressions.search( "hello" ) ) );
 
         TestEntity test = query.find();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLQuerying.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLQuerying.java b/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLQuerying.java
index 3079c84..d9cd3d1 100644
--- a/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLQuerying.java
+++ b/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLQuerying.java
@@ -62,7 +62,7 @@ import org.apache.zest.api.query.grammar.PropertyNotNullPredicate;
 import org.apache.zest.api.query.grammar.PropertyNullPredicate;
 import org.apache.zest.api.query.grammar.Variable;
 import org.apache.zest.api.service.ServiceDescriptor;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueComposite;
 import org.apache.zest.functional.Iterables;
 import org.apache.zest.index.sql.support.api.SQLQuerying;
@@ -108,7 +108,7 @@ public abstract class AbstractSQLQuerying
     private PostgreSQLTypeHelper _typeHelper;
 
     @Structure
-    private Module module;
+    private UnitOfWorkFactory uowf;
 
     @Structure
     private ZestSPI spi;
@@ -1052,7 +1052,7 @@ public abstract class AbstractSQLQuerying
                     // EntityComposite?
                     if( value instanceof EntityComposite )
                     {
-                        value = module.currentUnitOfWork().get(
+                        value = uowf.currentUnitOfWork().get(
                             (EntityComposite) value ).identity().get();
                     }
                     else
@@ -1853,7 +1853,7 @@ public abstract class AbstractSQLQuerying
                                                               fromClause, groupBy, having, qNameJoins, variables, values, valueSQLTypes );
                 } );
 
-                          // @formatter:on
+            // @formatter:on
         }
         else
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-sql/src/test/java/org/apache/zest/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/test/java/org/apache/zest/index/sql/postgresql/PostgreSQLDBIntegrityTest.java b/extensions/indexing-sql/src/test/java/org/apache/zest/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
index d6b2bcb..2e1389d 100644
--- a/extensions/indexing-sql/src/test/java/org/apache/zest/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
+++ b/extensions/indexing-sql/src/test/java/org/apache/zest/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
@@ -80,11 +80,11 @@ public class PostgreSQLDBIntegrityTest
     public void createAndRemoveEntityAndVerifyNoExtraDataLeftInDB()
         throws Exception
     {
-        UnitOfWork uow = this.module.newUnitOfWork();
+        UnitOfWork uow = this.uowf.newUnitOfWork();
         TestEntity entity = uow.newEntity( TestEntity.class );
         uow.complete();
 
-        uow = this.module.newUnitOfWork();
+        uow = this.uowf.newUnitOfWork();
         entity = uow.get( entity );
         SQLConfiguration config = uow.get( SQLConfiguration.class, PostgreSQLIndexQueryAssembler.DEFAULT_IDENTITY );
         String schemaName = config.schemaName().get();
@@ -127,16 +127,16 @@ public class PostgreSQLDBIntegrityTest
     public void createAndModifyEntity()
         throws Exception
     {
-        UnitOfWork uow = this.module.newUnitOfWork();
+        UnitOfWork uow = this.uowf.newUnitOfWork();
         TestEntity entity = uow.newEntity( TestEntity.class );
         uow.complete();
 
-        uow = this.module.newUnitOfWork();
+        uow = this.uowf.newUnitOfWork();
         entity = uow.get( entity );
         entity.testString().set( "NewTestString" );
         uow.complete();
 
-        uow = this.module.newUnitOfWork();
+        uow = this.uowf.newUnitOfWork();
         entity = uow.get( entity );
         Assert.assertEquals( "New value did not store in indexing.", "NewTestString", entity
             .testString().get() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/NoMetricsInstalledTest.java
----------------------------------------------------------------------
diff --git a/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/NoMetricsInstalledTest.java b/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/NoMetricsInstalledTest.java
index 8fc6cdc..672d32f 100644
--- a/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/NoMetricsInstalledTest.java
+++ b/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/NoMetricsInstalledTest.java
@@ -59,7 +59,7 @@ public class NoMetricsInstalledTest extends AbstractZestTest
 
     private void readEntity( int id )
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             Person p = uow.get( Person.class, "" + id );
@@ -74,7 +74,7 @@ public class NoMetricsInstalledTest extends AbstractZestTest
     private void createEntity( int id )
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             uow.newEntity( Person.class, "" + id );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/YammerTest.java
----------------------------------------------------------------------
diff --git a/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/YammerTest.java b/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/YammerTest.java
index 3f13774..716ee1f 100644
--- a/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/YammerTest.java
+++ b/extensions/metrics-yammer/src/test/java/org/apache/zest/metrics/yammer/YammerTest.java
@@ -60,7 +60,7 @@ public class YammerTest extends AbstractZestTest
 
     private void readEntity( int id )
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             Person p = uow.get( Person.class, "" + id );
@@ -75,7 +75,7 @@ public class YammerTest extends AbstractZestTest
     private void createEntity( int id )
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             uow.newEntity( Person.class, "" + id );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/migration/src/test/java/org/apache/zest/migration/MigrationTest.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/test/java/org/apache/zest/migration/MigrationTest.java b/extensions/migration/src/test/java/org/apache/zest/migration/MigrationTest.java
index 1e1f091..fe2b2fa 100644
--- a/extensions/migration/src/test/java/org/apache/zest/migration/MigrationTest.java
+++ b/extensions/migration/src/test/java/org/apache/zest/migration/MigrationTest.java
@@ -16,6 +16,7 @@ package org.apache.zest.migration;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.StringReader;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.hamcrest.CoreMatchers;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -53,6 +54,7 @@ public class MigrationTest
         throws AssemblyException
     {
         new EntityTestAssembler().assemble( module );
+        new DefaultUnitOfWorkAssembler().assemble( module );
 
         module.objects( MigrationEventLogger.class );
         module.importedServices( MigrationEventLogger.class ).importedBy( NewObjectImporter.class );
@@ -110,7 +112,7 @@ public class MigrationTest
                 }
             };
 
-            UnitOfWork uow = v1.module().newUnitOfWork();
+            UnitOfWork uow = v1.module().unitOfWorkFactory().newUnitOfWork();
             TestEntity1_0 entity = uow.newEntity( TestEntity1_0.class );
             entity.foo().set( "Some value" );
             entity.fooManyAssoc().add( entity );
@@ -141,7 +143,7 @@ public class MigrationTest
             BackupRestore testData = v1_1.module().findService( BackupRestore.class ).get();
             data_v1.transferTo( testData.restore() );
 
-            UnitOfWork uow = v1_1.module().newUnitOfWork();
+            UnitOfWork uow = v1_1.module().unitOfWorkFactory().newUnitOfWork();
             TestEntity1_1 entity = uow.get( TestEntity1_1.class, id );
             assertThat( "Property has been renamed", entity.newFoo().get(), CoreMatchers.equalTo( "Some value" ) );
             assertThat( "ManyAssociation has been renamed", entity.newFooManyAssoc().count(), CoreMatchers.equalTo( 1 ) );
@@ -169,7 +171,7 @@ public class MigrationTest
             // Test migration from 1.0 -> 2.0
             {
                 data_v1.transferTo( testData.restore() );
-                UnitOfWork uow = v2_0.module().newUnitOfWork();
+                UnitOfWork uow = v2_0.module().unitOfWorkFactory().newUnitOfWork();
                 TestEntity2_0 entity = uow.get( TestEntity2_0.class, id );
                 assertThat( "Property has been created", entity.bar().get(), CoreMatchers.equalTo( "Some value" ) );
                 assertThat( "Custom Property has been created", entity.customBar().get(), CoreMatchers.equalTo( "Hello Some value" ) );
@@ -198,7 +200,7 @@ public class MigrationTest
             // Test migration from 1.0 -> 3.0
             {
                 data_v1.transferTo( testData.restore() );
-                UnitOfWork uow = v3_0.module().newUnitOfWork();
+                UnitOfWork uow = v3_0.module().unitOfWorkFactory().newUnitOfWork();
                 org.apache.zest.migration.moved.TestEntity2_0 entity = uow.get( org.apache.zest.migration.moved.TestEntity2_0.class, id );
                 uow.complete();
             }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/reindexer/src/test/java/org/apache/zest/index/reindexer/ReindexerTest.java
----------------------------------------------------------------------
diff --git a/extensions/reindexer/src/test/java/org/apache/zest/index/reindexer/ReindexerTest.java b/extensions/reindexer/src/test/java/org/apache/zest/index/reindexer/ReindexerTest.java
index 8fd67cf..c95a8bc 100644
--- a/extensions/reindexer/src/test/java/org/apache/zest/index/reindexer/ReindexerTest.java
+++ b/extensions/reindexer/src/test/java/org/apache/zest/index/reindexer/ReindexerTest.java
@@ -93,7 +93,7 @@ public class ReindexerTest
 
         // ----> Create data and wipe index
 
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         EntityBuilder<MyEntity> eBuilder = uow.newEntityBuilder( MyEntity.class );
         MyEntity e = eBuilder.instance();
@@ -110,7 +110,7 @@ public class ReindexerTest
 
         module.<ReindexerService>findService( ReindexerService.class ).get().reindex(); // Reindex
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
 
         QueryBuilder<MyEntity> qBuilder = module.newQueryBuilder( MyEntity.class );
         qBuilder = qBuilder.where( eq( templateFor( MyEntity.class ).name(), TEST_NAME ) );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmPointFactory.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmPointFactory.java b/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmPointFactory.java
index f492b5c..934603c 100644
--- a/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmPointFactory.java
+++ b/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmPointFactory.java
@@ -20,27 +20,32 @@ import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceComposite;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 
-@Mixins(AlarmPointFactory.Mixin.class)
+@Mixins( AlarmPointFactory.Mixin.class )
 public interface AlarmPointFactory extends ServiceComposite
 {
-    AlarmPoint create(String identity, String systemName, String categoryName, AlarmClass alarmClass );
-    
+    AlarmPoint create( String identity, String systemName, String categoryName, AlarmClass alarmClass );
+
     abstract class Mixin
-        implements AlarmPointFactory {
+        implements AlarmPointFactory
+    {
+
+        @Structure
+        private UnitOfWorkFactory uowf;
 
         @Structure
-        private Module module;
-        
+        private ValueBuilderFactory vbf;
+
         @Override
         public AlarmPoint create( String identity, String systemName, String categoryName, AlarmClass alarmClass )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             EntityBuilder<AlarmPoint> builder = uow.newEntityBuilder( AlarmPoint.class, identity );
-            builder.instance().category().set( createCategory(categoryName) );
+            builder.instance().category().set( createCategory( categoryName ) );
             builder.instance().alarmClass().set( alarmClass );
 
             AlarmPoint.AlarmState prototype = builder.instanceFor( AlarmPoint.AlarmState.class );
@@ -53,14 +58,14 @@ public interface AlarmPointFactory extends ServiceComposite
 
         private AlarmStatus createNormalAlarmStatus()
         {
-            ValueBuilder<AlarmStatus> builder = module.newValueBuilder( AlarmStatus.class );
-            builder.prototypeFor(AlarmStatus.State.class).name().set( AlarmPoint.STATUS_NORMAL );
+            ValueBuilder<AlarmStatus> builder = vbf.newValueBuilder( AlarmStatus.class );
+            builder.prototypeFor( AlarmStatus.State.class ).name().set( AlarmPoint.STATUS_NORMAL );
             return builder.newInstance();
         }
 
         private AlarmCategory createCategory( String categoryName )
         {
-            ValueBuilder<AlarmCategory> builder = module.newValueBuilder( AlarmCategory.class );
+            ValueBuilder<AlarmCategory> builder = vbf.newValueBuilder( AlarmCategory.class );
             builder.prototype().name().set( categoryName );
             return builder.newInstance();
         }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmProxy.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmProxy.java b/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmProxy.java
index 6d2ef32..08f45bb 100644
--- a/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmProxy.java
+++ b/libraries/alarm/src/main/java/org/apache/zest/library/alarm/AlarmProxy.java
@@ -20,6 +20,7 @@ import java.util.List;
 import java.util.Locale;
 import org.apache.zest.api.common.Optional;
 import org.apache.zest.api.composite.TransientBuilder;
+import org.apache.zest.api.composite.TransientBuilderFactory;
 import org.apache.zest.api.composite.TransientComposite;
 import org.apache.zest.api.concern.Concerns;
 import org.apache.zest.api.injection.scope.Service;
@@ -27,9 +28,9 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceComposite;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.unitofwork.concern.UnitOfWorkConcern;
 import org.apache.zest.api.unitofwork.concern.UnitOfWorkPropagation;
 
@@ -38,9 +39,9 @@ import org.apache.zest.api.unitofwork.concern.UnitOfWorkPropagation;
 public interface AlarmProxy extends AlarmPoint, TransientComposite
 {
     @Mixins( FactoryMixin.class )
-    public interface Factory extends ServiceComposite
+    interface Factory extends ServiceComposite
     {
-        @UnitOfWorkPropagation( UnitOfWorkPropagation.Propagation.REQUIRED)
+        @UnitOfWorkPropagation( UnitOfWorkPropagation.Propagation.REQUIRED )
         AlarmProxy create( String identity, String systemName, String categoryName, AlarmClass alarmClass );
     }
 
@@ -48,7 +49,10 @@ public interface AlarmProxy extends AlarmPoint, TransientComposite
         implements Factory
     {
         @Structure
-        private Module module;
+        private TransientBuilderFactory tbf;
+
+        @Structure
+        private UnitOfWorkFactory uowf;
 
         @Service
         private AlarmPointFactory factory;
@@ -56,7 +60,7 @@ public interface AlarmProxy extends AlarmPoint, TransientComposite
         @Override
         public AlarmProxy create( String identity, String systemName, String categoryName, AlarmClass alarmClass )
         {
-            UnitOfWork unitOfWork = module.currentUnitOfWork();
+            UnitOfWork unitOfWork = uowf.currentUnitOfWork();
             AlarmPoint alarmPoint;
             try
             {
@@ -66,7 +70,7 @@ public interface AlarmProxy extends AlarmPoint, TransientComposite
             {
                 alarmPoint = factory.create( identity, systemName, categoryName, alarmClass );
             }
-            TransientBuilder<AlarmProxy> builder = module.newTransientBuilder( AlarmProxy.class );
+            TransientBuilder<AlarmProxy> builder = tbf.newTransientBuilder( AlarmProxy.class );
             builder.prototype().category().set( alarmPoint.category().get() );
             builder.prototype().alarmClass().set( alarmClass );
             builder.use( identity );
@@ -79,7 +83,7 @@ public interface AlarmProxy extends AlarmPoint, TransientComposite
     {
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Uses
         String identity;
@@ -199,7 +203,7 @@ public interface AlarmProxy extends AlarmPoint, TransientComposite
 
         private AlarmPoint findAlarmPoint()
         {
-            return module.currentUnitOfWork().get( AlarmPoint.class, identity );
+            return uowf.currentUnitOfWork().get( AlarmPoint.class, identity );
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmHistoryImplTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmHistoryImplTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmHistoryImplTest.java
index 2b27fc3..2589ed0 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmHistoryImplTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmHistoryImplTest.java
@@ -66,16 +66,16 @@ public class AlarmHistoryImplTest
         throws Exception
     {
         super.setUp();
-        module.newUnitOfWork();
+        uowf.newUnitOfWork();
     }
 
     @Override
     public void tearDown()
         throws Exception
     {
-        if (module.isUnitOfWorkActive())
+        if (uowf.isUnitOfWorkActive())
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             uow.discard();
         }
         super.tearDown();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmPointImplTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmPointImplTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmPointImplTest.java
index 1e0b3ca..fd79250 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmPointImplTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmPointImplTest.java
@@ -64,16 +64,16 @@ public class AlarmPointImplTest extends AbstractZestTest
         throws Exception
     {
         super.setUp();
-        module.newUnitOfWork();
+        uowf.newUnitOfWork();
     }
 
     @Override
     public void tearDown()
         throws Exception
     {
-        if( module.isUnitOfWorkActive() )
+        if( uowf.isUnitOfWorkActive() )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             uow.discard();
         }
         super.tearDown();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmProxyTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmProxyTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmProxyTest.java
index 718a822..8cd14b3 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmProxyTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmProxyTest.java
@@ -51,7 +51,7 @@ public class AlarmProxyTest extends AbstractZestTest
     public void givenAlarmPointWhenActivateExpectActivationEvent()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
 // START SNIPPET: documentation

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmServiceTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmServiceTest.java
index b08e189..e1d6ea0 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmServiceTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/AlarmServiceTest.java
@@ -67,16 +67,16 @@ public class AlarmServiceTest
         throws Exception
     {
         super.setUp();
-        module.newUnitOfWork();
+        uowf.newUnitOfWork();
     }
 
     @Override
     public void tearDown()
         throws Exception
     {
-        if (module.isUnitOfWorkActive())
+        if (uowf.isUnitOfWorkActive())
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             uow.discard();
         }
         super.tearDown();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/ExtendedAlarmModelTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/ExtendedAlarmModelTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/ExtendedAlarmModelTest.java
index 98079ac..0df9255 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/ExtendedAlarmModelTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/ExtendedAlarmModelTest.java
@@ -67,14 +67,14 @@ public class ExtendedAlarmModelTest
         throws Exception
     {
         super.setUp();
-        module.newUnitOfWork();
+        uowf.newUnitOfWork();
     }
 
     @Override
     public void tearDown()
         throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         if( uow != null )
         {
             uow.discard();
@@ -942,7 +942,7 @@ public class ExtendedAlarmModelTest
 
     private AlarmPoint createAlarm( String name )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<AlarmPoint> builder = uow.newEntityBuilder( AlarmPoint.class );
         builder.instance().category().set( createCategory( "Testing" ) );
         AlarmPoint.AlarmState state = builder.instanceFor( AlarmPoint.AlarmState.class );
@@ -961,7 +961,7 @@ public class ExtendedAlarmModelTest
 
     private AlarmPoint getAlarm( String identity )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         return uow.get( AlarmPoint.class, identity );
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/SimpleAlarmModelTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/SimpleAlarmModelTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/SimpleAlarmModelTest.java
index a7dd590..78ff217 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/SimpleAlarmModelTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/SimpleAlarmModelTest.java
@@ -67,14 +67,14 @@ public class SimpleAlarmModelTest
         throws Exception
     {
         super.setUp();
-        module.newUnitOfWork();
+        uowf.newUnitOfWork();
     }
 
     @Override
     public void tearDown()
         throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         if( uow != null )
         {
             uow.discard();
@@ -327,7 +327,7 @@ public class SimpleAlarmModelTest
 
     private AlarmPoint createAlarm( String name )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<AlarmPoint> builder = uow.newEntityBuilder( AlarmPoint.class );
         builder.instance().category().set( createCategory( "SimpleModelTest" ) );
         AlarmPoint.AlarmState state = builder.instanceFor( AlarmPoint.AlarmState.class );
@@ -346,7 +346,7 @@ public class SimpleAlarmModelTest
 
     private AlarmPoint getAlarm( String identity )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         return uow.get( AlarmPoint.class, identity );
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/alarm/src/test/java/org/apache/zest/library/alarm/StandardAlarmModelTest.java
----------------------------------------------------------------------
diff --git a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/StandardAlarmModelTest.java b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/StandardAlarmModelTest.java
index 69dab9b..84d10b6 100644
--- a/libraries/alarm/src/test/java/org/apache/zest/library/alarm/StandardAlarmModelTest.java
+++ b/libraries/alarm/src/test/java/org/apache/zest/library/alarm/StandardAlarmModelTest.java
@@ -68,14 +68,14 @@ public class StandardAlarmModelTest
         throws Exception
     {
         super.setUp();
-        module.newUnitOfWork();
+        uowf.newUnitOfWork();
     }
 
     @Override
     public void tearDown()
         throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         if( uow != null )
         {
             uow.discard();
@@ -453,7 +453,7 @@ public class StandardAlarmModelTest
 
     private AlarmPoint createAlarm( String name )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<AlarmPoint> builder = uow.newEntityBuilder( AlarmPoint.class );
         builder.instance().category().set( createCategory( "StandardModelTest" ) );
         AlarmPoint.AlarmState state = builder.instanceFor( AlarmPoint.AlarmState.class );
@@ -472,7 +472,7 @@ public class StandardAlarmModelTest
 
     private AlarmPoint getAlarm( String identity )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         return uow.get( AlarmPoint.class, identity );
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/conversion/src/main/java/org/apache/zest/library/conversion/values/ValueToEntityMixin.java
----------------------------------------------------------------------
diff --git a/libraries/conversion/src/main/java/org/apache/zest/library/conversion/values/ValueToEntityMixin.java b/libraries/conversion/src/main/java/org/apache/zest/library/conversion/values/ValueToEntityMixin.java
index ae9cf5d..02eeb15 100644
--- a/libraries/conversion/src/main/java/org/apache/zest/library/conversion/values/ValueToEntityMixin.java
+++ b/libraries/conversion/src/main/java/org/apache/zest/library/conversion/values/ValueToEntityMixin.java
@@ -39,11 +39,12 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.property.PropertyDescriptor;
 import org.apache.zest.api.unitofwork.EntityTypeNotFoundException;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueComposite;
 import org.apache.zest.api.value.ValueDescriptor;
 import org.apache.zest.functional.Iterables;
 import org.apache.zest.spi.ZestSPI;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
 
 import static org.apache.zest.library.conversion.values.Shared.STRING_COLLECTION_TYPE_SPEC;
@@ -125,6 +126,9 @@ public class ValueToEntityMixin
     private ZestSPI spi;
 
     @Structure
+    private UnitOfWorkFactory uowf;
+
+    @Structure
     private ModuleSpi module;
 
     @Override
@@ -299,7 +303,7 @@ public class ValueToEntityMixin
                 }
             }
         };
-        return module.currentUnitOfWork().newEntityBuilderWithState(
+        return uowf.currentUnitOfWork().newEntityBuilderWithState(
             entityType, identity, props, assocs, manyAssocs, namedAssocs
         );
     }
@@ -405,7 +409,7 @@ public class ValueToEntityMixin
                 }
             }
         };
-        return module.currentUnitOfWork().newEntityBuilderWithState(
+        return uowf.currentUnitOfWork().newEntityBuilderWithState(
             entityType, identity, props, assocs, manyAssocs, namedAssocs
         );
     }
@@ -484,7 +488,7 @@ public class ValueToEntityMixin
                         String assocId = (String) vState.propertyFor( vPropDesc.accessor() ).get();
                         if( assocId != null )
                         {
-                            eAssoc.set( module.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocId ) );
+                            eAssoc.set( uowf.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocId ) );
                         }
                         else
                         {
@@ -526,7 +530,7 @@ public class ValueToEntityMixin
                             for( String eachAssoc : vAssocState )
                             {
                                 eManyAssoc.add(
-                                    module.currentUnitOfWork().get( (Class) eAssocDesc.type(), eachAssoc )
+                                    uowf.currentUnitOfWork().get( (Class) eAssocDesc.type(), eachAssoc )
                                 );
                             }
                         }
@@ -570,7 +574,7 @@ public class ValueToEntityMixin
                             {
                                 eNamedAssoc.put(
                                     assocEntry.getKey(),
-                                    module.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocEntry.getValue() )
+                                    uowf.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocEntry.getValue() )
                                 );
                             }
                         }
@@ -624,7 +628,7 @@ public class ValueToEntityMixin
                         String assocId = (String) vState.propertyFor( vPropDesc.accessor() ).get();
                         if( assocId != null )
                         {
-                            eAssoc.set( module.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocId ) );
+                            eAssoc.set( uowf.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocId ) );
                         }
                         else
                         {
@@ -666,7 +670,7 @@ public class ValueToEntityMixin
                             vAssocState.forEach( eachAssoc ->
                             {
                                 eManyAssoc.add(
-                                    module.currentUnitOfWork().get( (Class<?>) eAssocDesc.type(), eachAssoc )
+                                    uowf.currentUnitOfWork().get( (Class<?>) eAssocDesc.type(), eachAssoc )
                                 );
                             } );
                         }
@@ -711,7 +715,7 @@ public class ValueToEntityMixin
                             {
                                 eNamedAssoc.put(
                                     assocEntry.getKey(),
-                                    module.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocEntry.getValue() )
+                                    uowf.currentUnitOfWork().get( (Class) eAssocDesc.type(), assocEntry.getValue() )
                                 );
                             }
                         }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/EntityToValueTest.java
----------------------------------------------------------------------
diff --git a/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/EntityToValueTest.java b/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/EntityToValueTest.java
index ef06960..b268a62 100644
--- a/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/EntityToValueTest.java
+++ b/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/EntityToValueTest.java
@@ -62,7 +62,7 @@ public class EntityToValueTest
     public void whenConvertingEntityToValueExpectCorrectValues()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             PersonEntity entity = setupPersonEntities( uow );
@@ -87,7 +87,7 @@ public class EntityToValueTest
     public void givenUnqualifiedValueWhenConvertingEntityExpectCorrectMapping()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             PersonEntity niclas = setupPersonEntities( uow );
@@ -112,7 +112,7 @@ public class EntityToValueTest
     public void givenUnqualifiedValue2WhenConvertingEntityExpectCorrectMapping()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             PersonEntity niclas = setupPersonEntities( uow );
@@ -137,7 +137,7 @@ public class EntityToValueTest
     public void givenQualifiedValueNotFromSameInterfaceWhenConvertingEntityExpectNonOptionalException()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             PersonEntity niclas = setupPersonEntities( uow );
@@ -158,7 +158,7 @@ public class EntityToValueTest
     public void whenConvertingEntityToValueUsingPrototypeOpportunityExpectCorrectValues()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             PersonEntity entity = setupPersonEntities( uow );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/NestedValuesConversionTest.java
----------------------------------------------------------------------
diff --git a/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/NestedValuesConversionTest.java b/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/NestedValuesConversionTest.java
index 4644d4d..4e8a087 100644
--- a/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/NestedValuesConversionTest.java
+++ b/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/NestedValuesConversionTest.java
@@ -52,7 +52,7 @@ public class NestedValuesConversionTest
     public void testNestedValuesConversion()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             FooEntity fooEntity = createFooEntity( uow, "Test nested values conversion" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/ValueToEntityTest.java
----------------------------------------------------------------------
diff --git a/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/ValueToEntityTest.java b/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/ValueToEntityTest.java
index 8197ebe..0441b84 100644
--- a/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/ValueToEntityTest.java
+++ b/libraries/conversion/src/test/java/org/apache/zest/library/conversion/values/ValueToEntityTest.java
@@ -76,7 +76,7 @@ public class ValueToEntityTest
     {
         // See http://en.wikipedia.org/wiki/Template:Flintstones_family_tree
         someBirthDate = createBirthDate( 1, 1, 1 );
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "InitialData" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "InitialData" ) ) )
         {
             ednaIdentity = createPerson( uow, "Edna", "Flintstone", someBirthDate ).identity().get();
             zekeIdentity = createPerson( uow, "Zeke", "Flintstone", someBirthDate ).identity().get();
@@ -96,7 +96,7 @@ public class ValueToEntityTest
         builder.prototype().spouse().set( ednaIdentity );
         builder.prototype().children().set( Arrays.asList( zekeIdentity, fredIdentity ) );
         PersonValue edValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreatingEntityFromQualifiedValue" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreatingEntityFromQualifiedValue" ) ) )
         {
             // START SNIPPET: creation
             ValueToEntity conversion = module.findService( ValueToEntity.class ).get();
@@ -129,7 +129,7 @@ public class ValueToEntityTest
         builder.prototype().spouse().set( ednaIdentity );
         builder.prototype().children().set( Arrays.asList( zekeIdentity, fredIdentity ) );
         PersonValue2 edValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreatingEntityFromUnqualifiedValue" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreatingEntityFromUnqualifiedValue" ) ) )
         {
             ValueToEntity conversion = module.findService( ValueToEntity.class ).get();
 
@@ -163,7 +163,7 @@ public class ValueToEntityTest
         builder.prototype().spouse().set( ednaIdentity );
         builder.prototype().children().set( Arrays.asList( zekeIdentity, fredIdentity ) );
         PersonValue3 edValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreatingEntityFromUnqualifiedValue" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreatingEntityFromUnqualifiedValue" ) ) )
         {
             ValueToEntity conversion = module.findService( ValueToEntity.class ).get();
 
@@ -197,7 +197,7 @@ public class ValueToEntityTest
         builder.prototype().spouse().set( ednaIdentity );
         builder.prototype().children().set( Arrays.asList( zekeIdentity, fredIdentity ) );
         PersonValue4 edValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreatingEntityFromUnqualifiedValue" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreatingEntityFromUnqualifiedValue" ) ) )
         {
             ValueToEntity conversion = module.findService( ValueToEntity.class ).get();
 
@@ -213,7 +213,7 @@ public class ValueToEntityTest
         throws UnitOfWorkCompletionException
     {
         String rickyIdentity;
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
         {
             PersonEntity ricky = createPerson( uow, "Ricky", "Slaghople", someBirthDate );
             ricky.spouse().set( uow.get( PersonEntity.class, ednaIdentity ) );
@@ -228,7 +228,7 @@ public class ValueToEntityTest
         builder.prototype().lastName().set( "Slaghoople" );
         builder.prototype().dateOfBirth().set( someBirthDate );
         PersonValue rickyNewStateValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "UpdateRickySlaghoople" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "UpdateRickySlaghoople" ) ) )
         {
             PersonEntity rickyEntity = uow.get( PersonEntity.class, rickyIdentity );
             // START SNIPPET: update
@@ -249,7 +249,7 @@ public class ValueToEntityTest
         throws UnitOfWorkCompletionException
     {
         String rickyIdentity;
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
         {
             PersonEntity ricky = createPerson( uow, "Ricky", "Slaghople", someBirthDate );
             ricky.spouse().set( uow.get( PersonEntity.class, ednaIdentity ) );
@@ -264,7 +264,7 @@ public class ValueToEntityTest
         builder.prototype().lastName().set( "Slaghoople" );
         builder.prototype().dateOfBirth().set( someBirthDate );
         PersonValue2 newStateValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "UpdateRickySlaghoople" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "UpdateRickySlaghoople" ) ) )
         {
             PersonEntity ricky = uow.get( PersonEntity.class, rickyIdentity );
 
@@ -284,7 +284,7 @@ public class ValueToEntityTest
         throws UnitOfWorkCompletionException
     {
         String rickyIdentity;
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
         {
             PersonEntity ricky = createPerson( uow, "Ricky", "Slaghople", someBirthDate );
             ricky.spouse().set( uow.get( PersonEntity.class, ednaIdentity ) );
@@ -299,7 +299,7 @@ public class ValueToEntityTest
         builder.prototype().lastName().set( "Slaghoople" );
         builder.prototype().dateOfBirth().set( someBirthDate );
         PersonValue3 newStateValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "UpdateRickySlaghoople" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "UpdateRickySlaghoople" ) ) )
         {
             PersonEntity ricky = uow.get( PersonEntity.class, rickyIdentity );
 
@@ -319,7 +319,7 @@ public class ValueToEntityTest
         throws UnitOfWorkCompletionException
     {
         String rickyIdentity;
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "CreateRickySlaghoopleWithTypo" ) ) )
         {
             PersonEntity ricky = createPerson( uow, "Ricky", "Slaghople", someBirthDate );
             ricky.spouse().set( uow.get( PersonEntity.class, ednaIdentity ) );
@@ -334,7 +334,7 @@ public class ValueToEntityTest
         builder.prototype().lastName().set( "Slaghoople" );
         builder.prototype().dateOfBirth().set( someBirthDate );
         PersonValue4 newStateValue = builder.newInstance();
-        try( UnitOfWork uow = module.newUnitOfWork( newUsecase( "UpdateRickySlaghoopleWontWork" ) ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "UpdateRickySlaghoopleWontWork" ) ) )
         {
             PersonEntity ricky = uow.get( PersonEntity.class, rickyIdentity );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing-jdbm/src/test/java/org/apache/zest/library/eventsourcing/domain/source/jdbm/JdbmEventStoreServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing-jdbm/src/test/java/org/apache/zest/library/eventsourcing/domain/source/jdbm/JdbmEventStoreServiceTest.java b/libraries/eventsourcing-jdbm/src/test/java/org/apache/zest/library/eventsourcing/domain/source/jdbm/JdbmEventStoreServiceTest.java
index 858f29c..f0a2e11 100644
--- a/libraries/eventsourcing-jdbm/src/test/java/org/apache/zest/library/eventsourcing/domain/source/jdbm/JdbmEventStoreServiceTest.java
+++ b/libraries/eventsourcing-jdbm/src/test/java/org/apache/zest/library/eventsourcing/domain/source/jdbm/JdbmEventStoreServiceTest.java
@@ -66,14 +66,14 @@ public class JdbmEventStoreServiceTest
         @Test
         public void testDomainEvent() throws UnitOfWorkCompletionException, IOException
         {
-            UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Create entity" ));
+            UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Create entity" ));
             TestEntity entity = uow.newEntity( TestEntity.class );
             uow.complete();
 
             int count = 10;
             for (int i = 0; i < count; i++)
             {
-                uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Change description" ));
+                uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Change description" ));
                 uow.setMetaInfo( new Principal()
                 {
                     public String getName()

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing-rest/src/test/java/org/apache/zest/library/eventsourcing/domain/rest/server/DomainEventSourceResourceSample.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing-rest/src/test/java/org/apache/zest/library/eventsourcing/domain/rest/server/DomainEventSourceResourceSample.java b/libraries/eventsourcing-rest/src/test/java/org/apache/zest/library/eventsourcing/domain/rest/server/DomainEventSourceResourceSample.java
index d55dac2..b5b6030 100644
--- a/libraries/eventsourcing-rest/src/test/java/org/apache/zest/library/eventsourcing/domain/rest/server/DomainEventSourceResourceSample.java
+++ b/libraries/eventsourcing-rest/src/test/java/org/apache/zest/library/eventsourcing/domain/rest/server/DomainEventSourceResourceSample.java
@@ -77,7 +77,7 @@ public class DomainEventSourceResourceSample
         component.getDefaultHost().attach( "/ping", assembler.module().newObject( PingResource.class ) );
         component.start();
 
-        generateTestData(assembler.module());
+        generateTestData(assembler.module().unitOfWorkFactory());
     }
 
     private static void generateTestData(UnitOfWorkFactory unitOfWorkFactory) throws UnitOfWorkCompletionException

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/application/ApplicationEventTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/application/ApplicationEventTest.java b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/application/ApplicationEventTest.java
index 9f38d7f..911eeb7 100644
--- a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/application/ApplicationEventTest.java
+++ b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/application/ApplicationEventTest.java
@@ -103,21 +103,21 @@ public class ApplicationEventTest
             }
         };
 
-        UnitOfWork uow1 = module.newUnitOfWork( UsecaseBuilder.newUsecase( "User signup" ) );
+        UnitOfWork uow1 = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "User signup" ) );
         uow1.setMetaInfo( administratorPrincipal );
         users.signup( null, "user1", Arrays.asList( "news-a", "news-b" ) );
         uow1.complete();
 
         Thread.sleep( 1 ); // For UoWs not getting the same `currentTime`
 
-        UnitOfWork uow2 = module.newUnitOfWork();
+        UnitOfWork uow2 = uowf.newUnitOfWork();
         uow2.setMetaInfo( administratorPrincipal );
         users.signup( null, "user2", Collections.EMPTY_LIST );
         uow2.complete();
 
         Thread.sleep( 1 ); // For UoWs not getting the same `currentTime`
 
-        UnitOfWork uow3 = module.newUnitOfWork();
+        UnitOfWork uow3 = uowf.newUnitOfWork();
         uow3.setMetaInfo( administratorPrincipal );
         users.signup( null, "user3", Collections.singletonList( "news-c" ) );
         uow3.complete();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/DomainEventTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/DomainEventTest.java b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/DomainEventTest.java
index dcd5bee..c8fe3a6 100644
--- a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/DomainEventTest.java
+++ b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/DomainEventTest.java
@@ -78,7 +78,7 @@ public class DomainEventTest
         };
 
         // Perform UoW with usecase defined
-        UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Change description" ));
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Change description" ));
         uow.setMetaInfo( administratorPrincipal );
 
         TestEntity entity = uow.newEntity( TestEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/DomainEventTrackerTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/DomainEventTrackerTest.java b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/DomainEventTrackerTest.java
index 9f357f5..1e1ce5e 100644
--- a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/DomainEventTrackerTest.java
+++ b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/DomainEventTrackerTest.java
@@ -72,7 +72,7 @@ public class DomainEventTrackerTest
     @Test
     public void testDomainEvent() throws UnitOfWorkCompletionException, IOException
     {
-        UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Change description" ));
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Change description" ));
         uow.setMetaInfo( new Principal()
         {
             public String getName()

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventRouterTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventRouterTest.java b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventRouterTest.java
index da2b1eb..b8785ee 100644
--- a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventRouterTest.java
+++ b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventRouterTest.java
@@ -18,6 +18,7 @@ package org.apache.zest.library.eventsourcing.domain.source.helper;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.json.JSONException;
 import org.json.JSONObject;
 import org.junit.Before;
@@ -49,6 +50,7 @@ public class EventRouterTest
             public void assemble( ModuleAssembly module ) throws AssemblyException
             {
                 module.values( UnitOfWorkDomainEventsValue.class, DomainEventValue.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventsTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventsTest.java b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventsTest.java
index 575ab5b..0402c4f 100644
--- a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventsTest.java
+++ b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/EventsTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.zest.library.eventsourcing.domain.source.helper;
 
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
@@ -55,6 +56,7 @@ public class EventsTest
             public void assemble( ModuleAssembly module ) throws AssemblyException
             {
                 module.values( UnitOfWorkDomainEventsValue.class, DomainEventValue.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/UnitOfWorkRouterTest.java
----------------------------------------------------------------------
diff --git a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/UnitOfWorkRouterTest.java b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/UnitOfWorkRouterTest.java
index 0f6a970..94b1d56 100644
--- a/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/UnitOfWorkRouterTest.java
+++ b/libraries/eventsourcing/src/test/java/org/apache/zest/library/eventsourcing/domain/source/helper/UnitOfWorkRouterTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.zest.library.eventsourcing.domain.source.helper;
 
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.hamcrest.CoreMatchers;
 import org.junit.Assert;
 import org.junit.Before;
@@ -53,6 +54,7 @@ public class UnitOfWorkRouterTest
             public void assemble( ModuleAssembly module ) throws AssemblyException
             {
                 module.values( UnitOfWorkDomainEventsValue.class, DomainEventValue.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/lang-scala/src/test/scala/org/apache/zest/library/scala/HelloWorldCompositeTest.java
----------------------------------------------------------------------
diff --git a/libraries/lang-scala/src/test/scala/org/apache/zest/library/scala/HelloWorldCompositeTest.java b/libraries/lang-scala/src/test/scala/org/apache/zest/library/scala/HelloWorldCompositeTest.java
index a01b870..0f53355 100644
--- a/libraries/lang-scala/src/test/scala/org/apache/zest/library/scala/HelloWorldCompositeTest.java
+++ b/libraries/lang-scala/src/test/scala/org/apache/zest/library/scala/HelloWorldCompositeTest.java
@@ -18,6 +18,7 @@ import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.ModuleAssembly;
 import org.apache.zest.bootstrap.SingletonAssembler;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.index.rdf.assembly.RdfMemoryStoreAssembler;
 import org.apache.zest.spi.query.IndexExporter;
 import org.apache.zest.test.EntityTestAssembler;
@@ -84,11 +85,12 @@ public class HelloWorldCompositeTest
 
                 new EntityTestAssembler().assemble( module );
                 new RdfMemoryStoreAssembler().assemble( module );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 
         // Create and update Entity
-        UnitOfWork uow = assembler.module().newUnitOfWork();
+        UnitOfWork uow = assembler.module().unitOfWorkFactory().newUnitOfWork();
         try
         {
             Commands entity = uow.newEntity( Commands.class );
@@ -106,7 +108,7 @@ public class HelloWorldCompositeTest
         assembler.module().findService( IndexExporter.class ).get().exportReadableToStream( System.out );
 
         // Find it
-        uow = assembler.module().newUnitOfWork();
+        uow = assembler.module().unitOfWorkFactory().newUnitOfWork();
         try
         {
             Data data = uow.newQuery( assembler.module()

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/logging/src/test/java/org/apache/zest/library/logging/DebuggingTest.java
----------------------------------------------------------------------
diff --git a/libraries/logging/src/test/java/org/apache/zest/library/logging/DebuggingTest.java b/libraries/logging/src/test/java/org/apache/zest/library/logging/DebuggingTest.java
index a424aba..b86ab71 100644
--- a/libraries/logging/src/test/java/org/apache/zest/library/logging/DebuggingTest.java
+++ b/libraries/logging/src/test/java/org/apache/zest/library/logging/DebuggingTest.java
@@ -60,7 +60,7 @@ public class DebuggingTest
     @Test
     public void whenCallingMethodThenExpectDebugEntityCreated()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             // There is no Query capability available for Libraries, since that sits in Extensions.

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/logging/src/test/java/org/apache/zest/library/logging/TracingTest.java
----------------------------------------------------------------------
diff --git a/libraries/logging/src/test/java/org/apache/zest/library/logging/TracingTest.java b/libraries/logging/src/test/java/org/apache/zest/library/logging/TracingTest.java
index 6438fc4..06dd6b9 100644
--- a/libraries/logging/src/test/java/org/apache/zest/library/logging/TracingTest.java
+++ b/libraries/logging/src/test/java/org/apache/zest/library/logging/TracingTest.java
@@ -70,7 +70,7 @@ public class TracingTest
         SomeService sc = module.findService( SomeService.class ).get();
         assertEquals( 123, sc.doSomethingImportant() );
         assertEquals( 456, sc.doSomethingLessImportant() );
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         QueryBuilder<TraceRecord> builder = module.newQueryBuilder( TraceRecord.class );
         Query<TraceRecord> query = uow.newQuery( builder );
         // IS sorting needed??
@@ -91,7 +91,7 @@ public class TracingTest
         SomeService2 sc = module.findService( SomeService2.class ).get();
         assertEquals( 123, sc.doSomethingImportant() );
         assertEquals( 456, sc.doSomethingLessImportant() );
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         QueryBuilder<TraceRecord> builder = module.newQueryBuilder( TraceRecord.class );
         Query<TraceRecord> query = uow.newQuery( builder );
         // IS sorting needed??
@@ -115,7 +115,7 @@ public class TracingTest
         SomeService sc = module.findService( SomeService.class ).get();
         assertEquals( 123, sc.doSomethingImportant() );
         assertEquals( 789, sc.doSomethingModeratelyImportant() );
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             QueryBuilder<TraceRecord> builder = module.newQueryBuilder( TraceRecord.class );
@@ -154,7 +154,7 @@ public class TracingTest
         SomeService sc = module.findService( SomeService.class ).get();
         assertEquals( 123, sc.doSomethingImportant() );
         assertEquals( 753, sc.doSomethingInsanelyImportant() );
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         QueryBuilder<TraceRecord> builder = module.newQueryBuilder( TraceRecord.class );
         Query<TraceRecord> query = uow.newQuery( builder );
         // IS sorting needed??

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntitySerializerTest.java
----------------------------------------------------------------------
diff --git a/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntitySerializerTest.java b/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntitySerializerTest.java
index 49edb94..89054bb 100755
--- a/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntitySerializerTest.java
+++ b/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntitySerializerTest.java
@@ -95,7 +95,7 @@ public class EntitySerializerTest
     void createDummyData()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             ValueBuilder<TestValue> valueBuilder = module.newValueBuilder( TestValue.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntityTypeSerializerTest.java
----------------------------------------------------------------------
diff --git a/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntityTypeSerializerTest.java b/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntityTypeSerializerTest.java
index 23b4eca..dbdb77a 100644
--- a/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntityTypeSerializerTest.java
+++ b/libraries/rdf/src/test/java/org/apache/zest/library/rdf/entity/EntityTypeSerializerTest.java
@@ -81,7 +81,7 @@ public class EntityTypeSerializerTest
 
     void createDummyData() throws UnitOfWorkCompletionException
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             ValueBuilder<Test2Value> vb2 = module.newValueBuilder( Test2Value.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContextResourceClientFactoryTest.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContextResourceClientFactoryTest.java b/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContextResourceClientFactoryTest.java
index cab3481..c1d0595 100644
--- a/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContextResourceClientFactoryTest.java
+++ b/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContextResourceClientFactoryTest.java
@@ -22,7 +22,9 @@ import java.io.File;
 import java.io.IOException;
 import java.util.Collections;
 import org.apache.zest.api.type.HasTypes;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.UsecaseBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.hamcrest.CoreMatchers;
 import org.junit.After;
 import org.junit.Assert;
@@ -391,7 +393,7 @@ public class ContextResourceClientFactoryTest
         @Override
         protected Uniform createRoot( Request request, Response response )
         {
-            return module.newObject( RootResource.class, this );
+            return objectFactory.newObject( RootResource.class, this );
         }
     }
 
@@ -554,16 +556,19 @@ public class ContextResourceClientFactoryTest
         private static int count = 0;
 
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
+
+        @Structure
+        ValueBuilderFactory vbf;
 
         public TestResult queryWithValue( TestQuery query )
         {
-            return module.newValueFromSerializedState( TestResult.class, "{'xyz':'"+query.abc().get()+"'}" );
+            return vbf.newValueFromSerializedState( TestResult.class, "{'xyz':'"+query.abc().get()+"'}" );
         }
 
         public TestResult queryWithoutValue()
         {
-            return module.newValueFromSerializedState( TestResult.class, "{'xyz':'bar'}" );
+            return vbf.newValueFromSerializedState( TestResult.class, "{'xyz':'bar'}" );
         }
 
         public String queryWithStringResult( TestQuery query )
@@ -594,7 +599,7 @@ public class ContextResourceClientFactoryTest
             count++;
             if( count % 3 != 0 )
             {
-                module.currentUnitOfWork().addUnitOfWorkCallback( new UnitOfWorkCallback()
+                uowf.currentUnitOfWork().addUnitOfWorkCallback( new UnitOfWorkCallback()
                 {
                     public void beforeCompletion()
                         throws UnitOfWorkCompletionException

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContinuousIntegrationTest.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContinuousIntegrationTest.java b/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContinuousIntegrationTest.java
index 365bd83..da652d1 100644
--- a/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContinuousIntegrationTest.java
+++ b/libraries/rest-client/src/test/java/org/apache/zest/library/rest/client/ContinuousIntegrationTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.zest.library.rest.client;
 
+import org.apache.zest.api.composite.TransientBuilderFactory;
 import org.hamcrest.CoreMatchers;
 import org.junit.After;
 import org.junit.Assert;
@@ -372,7 +373,7 @@ public class ContinuousIntegrationTest
         @Override
         protected Uniform createRoot( Request request, Response response )
         {
-            return module.newObject( RootResource.class, this );
+            return objectFactory.newObject( RootResource.class, this );
         }
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextResource.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextResource.java b/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextResource.java
index f673e6e..67c8584 100644
--- a/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextResource.java
+++ b/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextResource.java
@@ -1,12 +1,11 @@
 /**
- *
  * Copyright 2009-2011 Rickard Öberg AB
  *
  * Licensed 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
+ * 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,
@@ -37,10 +36,10 @@ import org.apache.zest.api.entity.EntityComposite;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
-import org.apache.zest.api.property.PropertyDescriptor;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.EntityTypeNotFoundException;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
 import org.apache.zest.api.value.ValueComposite;
 import org.apache.zest.api.value.ValueDescriptor;
@@ -83,6 +82,9 @@ public class ContextResource
 
     // API fields
     @Structure
+    private UnitOfWorkFactory uowf;
+
+    @Structure
     protected Module module;
 
     // Private state
@@ -203,7 +205,7 @@ public class ContextResource
     {
         try
         {
-            T composite = module.currentUnitOfWork().get( entityClass, id );
+            T composite = uowf.currentUnitOfWork().get( entityClass, id );
             current().select( composite );
             return composite;
         }
@@ -216,7 +218,7 @@ public class ContextResource
     protected <T> T selectFromManyAssociation( ManyAssociation<T> manyAssociation, String id )
         throws ResourceException
     {
-        T entity = (T) module.currentUnitOfWork().get( Object.class, id );
+        T entity = (T) uowf.currentUnitOfWork().get( Object.class, id );
         if( !manyAssociation.contains( entity ) )
         {
             throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND );
@@ -225,13 +227,13 @@ public class ContextResource
         current().select( entity );
         return entity;
     }
-    
+
     protected <T> T selectFromNamedAssociation( NamedAssociation<T> namedAssociation, String id )
         throws ResourceException
     {
-        T entity = (T) module.currentUnitOfWork().get( Object.class, id );
+        T entity = (T) uowf.currentUnitOfWork().get( Object.class, id );
         String name = namedAssociation.nameOf( entity );
-        if(name == null)
+        if( name == null )
         {
             throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND );
         }
@@ -677,7 +679,7 @@ public class ContextResource
                                                                                    .isAvailable() || request
                                                                                                          .getResourceRef()
                                                                                                          .getQuery() != null || queryMethod
-                .getParameterTypes()[ 0 ].equals( Response.class ) ) ) )
+                                                                                   .getParameterTypes()[ 0 ].equals( Response.class ) ) ) )
         {
             // Show form
             try
@@ -871,7 +873,7 @@ public class ContextResource
         {
             ValueDescriptor valueDescriptor = module.valueDescriptor( valueType.getName() );
 
-            valueDescriptor.state().properties().forEach(propertyDescriptor -> {
+            valueDescriptor.state().properties().forEach( propertyDescriptor -> {
                 String value = getValue( propertyDescriptor.qualifiedName().name(), queryAsForm, entityAsForm );
                 if( value == null )
                 {
@@ -882,7 +884,7 @@ public class ContextResource
                     }
                 }
                 form.add( propertyDescriptor.qualifiedName().name(), value );
-            });
+            } );
         }
         else if( valueType.isInterface() && interactionMethod.getParameterTypes().length == 1 )
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextRestlet.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextRestlet.java b/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextRestlet.java
index 7931255..100e639 100644
--- a/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextRestlet.java
+++ b/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/api/ContextRestlet.java
@@ -1,12 +1,11 @@
 /**
- *
  * Copyright 2009-2011 Rickard Öberg AB
  *
  * Licensed 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
+ * 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,
@@ -24,9 +23,10 @@ import java.util.Map;
 import org.apache.zest.api.cache.CacheOptions;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.object.ObjectFactory;
 import org.apache.zest.api.unitofwork.ConcurrentEntityModificationException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.Usecase;
 import org.apache.zest.api.usecase.UsecaseBuilder;
 import org.apache.zest.library.rest.server.restlet.ResponseWriterDelegator;
@@ -53,7 +53,10 @@ public abstract class ContextRestlet
     extends Restlet
 {
     @Structure
-    protected Module module;
+    protected ObjectFactory objectFactory;
+
+    @Structure
+    protected UnitOfWorkFactory uowf;
 
     @Service
     private CommandResult commandResult;
@@ -61,7 +64,7 @@ public abstract class ContextRestlet
     @Service
     private ResponseWriterDelegator responseWriter;
 
-    private Map<Class, Uniform> subResources = Collections.synchronizedMap( new HashMap<Class, Uniform>() );
+    private Map<Class, Uniform> subResources = Collections.synchronizedMap( new HashMap<>() );
 
     @Override
     public void handle( Request request, Response response )
@@ -83,7 +86,7 @@ public abstract class ContextRestlet
                 Reference ref = request.getResourceRef();
                 List<String> segments = ref.getScheme()
                                             .equals( "riap" ) ? ref.getRelativeRef( new Reference( "riap://application/" ) )
-                    .getSegments() : ref.getRelativeRef().getSegments();
+                                            .getSegments() : ref.getRelativeRef().getSegments();
 
                 // Handle conversion of verbs into standard interactions
                 if( segments.get( segments.size() - 1 ).equals( "" ) )
@@ -106,7 +109,7 @@ public abstract class ContextRestlet
                 Usecase usecase = UsecaseBuilder.buildUsecase( getUsecaseName( request ) )
                     .withMetaInfo( request.getMethod().isSafe() ? CacheOptions.ALWAYS : CacheOptions.NEVER )
                     .newUsecase();
-                UnitOfWork uow = module.newUnitOfWork( usecase );
+                UnitOfWork uow = uowf.newUnitOfWork( usecase );
 
                 ObjectSelection.newSelection();
 
@@ -194,7 +197,7 @@ public abstract class ContextRestlet
                                 // Check if last modified and tag should be set
                                 if( validity != null )
                                 {
-                                    UnitOfWork lastModifiedUoW = module.newUnitOfWork();
+                                    UnitOfWork lastModifiedUoW = uowf.newUnitOfWork();
 
                                     try
                                     {
@@ -244,7 +247,7 @@ public abstract class ContextRestlet
         if( subResource == null )
         {
             // Instantiate and store subresource instance
-            subResource = module.newObject( subResourceClass, this );
+            subResource = objectFactory.newObject( subResourceClass, this );
             subResources.put( subResourceClass, subResource );
         }
 


[5/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/visibility/VisibilityInUnitOfWorkTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/visibility/VisibilityInUnitOfWorkTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/visibility/VisibilityInUnitOfWorkTest.java
index bae6c61..55662db 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/visibility/VisibilityInUnitOfWorkTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/visibility/VisibilityInUnitOfWorkTest.java
@@ -16,7 +16,6 @@
 */
 package org.apache.zest.runtime.visibility;
 
-import org.junit.Test;
 import org.apache.zest.api.common.Visibility;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
@@ -25,17 +24,18 @@ import org.apache.zest.api.service.ServiceReference;
 import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueSerialization;
-import org.apache.zest.bootstrap.ApplicationAssembler;
 import org.apache.zest.bootstrap.ApplicationAssembly;
-import org.apache.zest.bootstrap.ApplicationAssemblyFactory;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.Energy4Java;
 import org.apache.zest.bootstrap.LayerAssembly;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.entitystore.memory.MemoryEntityStoreService;
 import org.apache.zest.spi.uuid.UuidIdentityGeneratorService;
 import org.apache.zest.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.junit.Test;
 
 public class VisibilityInUnitOfWorkTest
 {
@@ -60,19 +60,19 @@ public class VisibilityInUnitOfWorkTest
             implements YourService
         {
             @Structure
-            private Module module;
+            private UnitOfWorkFactory uowf;
 
             @Override
             public void create()
             {
-                UnitOfWork uow = module.currentUnitOfWork();
+                UnitOfWork uow = uowf.currentUnitOfWork();
                 YourEntity entity = uow.newEntity( YourEntity.class, "345" );
             }
 
             @Override
             public YourEntity get()
             {
-                UnitOfWork uow = module.currentUnitOfWork();
+                UnitOfWork uow = uowf.currentUnitOfWork();
                 return uow.get( YourEntity.class, "345" );
             }
         }
@@ -114,12 +114,12 @@ public class VisibilityInUnitOfWorkTest
             private YourService service;
 
             @Structure
-            private Module module;
+            private UnitOfWorkFactory uowf;
 
             @Override
             public void create()
             {
-                try (UnitOfWork uow = module.newUnitOfWork())
+                try (UnitOfWork uow = uowf.newUnitOfWork())
                 {
                     uow.newEntity( MyEntity.class, "123" );
                     MyEntity entity1 = uow.get( MyEntity.class, "123" );
@@ -134,26 +134,25 @@ public class VisibilityInUnitOfWorkTest
         throws AssemblyException
     {
         Energy4Java zest = new Energy4Java();
-        return zest.newApplication( new ApplicationAssembler()
-        {
-            @Override
-            public ApplicationAssembly assemble( ApplicationAssemblyFactory appFactory )
-                throws AssemblyException
-            {
-                ApplicationAssembly appAssembly = appFactory.newApplicationAssembly();
-                LayerAssembly layer1 = appAssembly.layer( "layer1" );
-                ModuleAssembly myModule = layer1.module( "My Module" );
-                ModuleAssembly yourModule = layer1.module( "Your Module" );
-                ModuleAssembly infraModule = layer1.module( "Infra Module" );
-                myModule.services( MyService.class );
-                myModule.entities( MyEntity.class );
-                yourModule.entities( YourEntity.class );
-                yourModule.services( YourService.class ).visibleIn( Visibility.layer );
-                infraModule.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
-                infraModule.services( UuidIdentityGeneratorService.class ).visibleIn( Visibility.layer );
-                infraModule.services( OrgJsonValueSerializationService.class ).visibleIn( Visibility.layer).taggedWith( ValueSerialization.Formats.JSON );
-                return appAssembly;
-            }
+        return zest.newApplication( appFactory -> {
+            ApplicationAssembly appAssembly = appFactory.newApplicationAssembly();
+            LayerAssembly layer1 = appAssembly.layer( "layer1" );
+            ModuleAssembly myModule = layer1.module( "My Module" );
+            ModuleAssembly yourModule = layer1.module( "Your Module" );
+            ModuleAssembly infraModule = layer1.module( "Infra Module" );
+            myModule.services( MyService.class );
+            myModule.entities( MyEntity.class );
+            new DefaultUnitOfWorkAssembler().assemble( myModule );
+            yourModule.entities( YourEntity.class );
+            yourModule.services( YourService.class ).visibleIn( Visibility.layer );
+            new DefaultUnitOfWorkAssembler().assemble( yourModule );
+            infraModule.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
+            infraModule.services( UuidIdentityGeneratorService.class ).visibleIn( Visibility.layer );
+            infraModule.services( OrgJsonValueSerializationService.class )
+                .visibleIn( Visibility.layer )
+                .taggedWith( ValueSerialization.Formats.JSON );
+            new DefaultUnitOfWorkAssembler().assemble( infraModule );
+            return appAssembly;
         } );
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/JSONMapEntityStoreMixin.java b/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
index ef78cce..8dedcfd 100755
--- a/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
+++ b/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
@@ -58,7 +58,7 @@ import org.apache.zest.spi.entitystore.EntityStoreException;
 import org.apache.zest.spi.entitystore.EntityStoreSPI;
 import org.apache.zest.spi.entitystore.EntityStoreUnitOfWork;
 import org.apache.zest.spi.entitystore.StateCommitter;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
 import org.json.JSONException;
 import org.json.JSONObject;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/MapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/MapEntityStoreMixin.java b/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/MapEntityStoreMixin.java
index ec001b1..d553437 100755
--- a/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/MapEntityStoreMixin.java
+++ b/core/spi/src/main/java/org/apache/zest/spi/entitystore/helpers/MapEntityStoreMixin.java
@@ -55,7 +55,7 @@ import org.apache.zest.spi.entitystore.EntityStoreException;
 import org.apache.zest.spi.entitystore.EntityStoreSPI;
 import org.apache.zest.spi.entitystore.EntityStoreUnitOfWork;
 import org.apache.zest.spi.entitystore.StateCommitter;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
 import org.json.JSONArray;
 import org.json.JSONException;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/spi/src/main/java/org/apache/zest/spi/module/ModelModule.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/zest/spi/module/ModelModule.java b/core/spi/src/main/java/org/apache/zest/spi/module/ModelModule.java
deleted file mode 100644
index 4445697..0000000
--- a/core/spi/src/main/java/org/apache/zest/spi/module/ModelModule.java
+++ /dev/null
@@ -1,107 +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.zest.spi.module;
-
-import java.util.function.Function;
-import org.apache.zest.api.composite.ModelDescriptor;
-
-/**
- * TODO
- */
-public class ModelModule<T extends ModelDescriptor>
-{
-
-    public static Function<ModelModule<?>, String> toStringFunction = item -> item.model()
-               .types()
-               .iterator()
-               .next()
-               .getName() + "[" + item.module().name() + "]";
-
-    public static <T extends ModelDescriptor> Function<T, ModelModule<T>> modelModuleFunction( final ModuleSpi module )
-    {
-        return model1 -> new ModelModule<>( module, model1 );
-    }
-
-    public static Function<ModelModule<? extends ModelDescriptor>, ModelDescriptor> modelFunction()
-    {
-        return new Function<ModelModule<? extends ModelDescriptor>, ModelDescriptor>()
-        {
-            @Override
-            public ModelDescriptor apply( ModelModule<? extends ModelDescriptor> modelModule )
-            {
-                return modelModule.model();
-            }
-        };
-    }
-
-    private final ModuleSpi module;
-    private final T model;
-
-    public ModelModule( ModuleSpi module, T model )
-    {
-        this.module = module;
-        this.model = model;
-    }
-
-    public ModuleSpi module()
-    {
-        return module;
-    }
-
-    public T model()
-    {
-        return model;
-    }
-
-    @Override
-    public boolean equals( Object o )
-    {
-        if( this == o )
-        {
-            return true;
-        }
-        if( o == null || getClass() != o.getClass() )
-        {
-            return false;
-        }
-
-        ModelModule that = (ModelModule) o;
-
-        if( model != null ? !model.equals( that.model ) : that.model != null )
-        {
-            return false;
-        }
-
-        return !( module != null ? !module.equals( that.module ) : that.module != null );
-    }
-
-    @Override
-    public int hashCode()
-    {
-        int result = module != null ? module.hashCode() : 0;
-        result = 31 * result + ( model != null ? model.hashCode() : 0 );
-        return result;
-    }
-
-    @Override
-    public String toString()
-    {
-        return module.name() + ":" + model;
-    }
-}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/spi/src/main/java/org/apache/zest/spi/module/ModuleSpi.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/zest/spi/module/ModuleSpi.java b/core/spi/src/main/java/org/apache/zest/spi/module/ModuleSpi.java
index 3057b05..cb5208c 100644
--- a/core/spi/src/main/java/org/apache/zest/spi/module/ModuleSpi.java
+++ b/core/spi/src/main/java/org/apache/zest/spi/module/ModuleSpi.java
@@ -19,7 +19,10 @@ package org.apache.zest.spi.module;
 import java.util.stream.Stream;
 import org.apache.zest.api.composite.ModelDescriptor;
 import org.apache.zest.api.entity.IdentityGenerator;
+import org.apache.zest.api.metrics.MetricsProvider;
 import org.apache.zest.api.service.ServiceReference;
+import org.apache.zest.spi.structure.TypeLookup;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.value.ValueSerialization;
 import org.apache.zest.spi.entitystore.EntityStore;
@@ -41,4 +44,8 @@ public interface ModuleSpi extends Module
     Stream<ModelModule<? extends ModelDescriptor>> findVisibleObjectTypes();
 
     Stream<ServiceReference<?>> findVisibleServiceTypes();
+
+    TypeLookup typeLookup();
+
+    MetricsProvider metricsProvider();
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/spi/src/main/java/org/apache/zest/spi/structure/ModelModule.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/zest/spi/structure/ModelModule.java b/core/spi/src/main/java/org/apache/zest/spi/structure/ModelModule.java
new file mode 100644
index 0000000..6b584ae
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/zest/spi/structure/ModelModule.java
@@ -0,0 +1,107 @@
+/*
+ * 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.zest.spi.structure;
+
+import java.util.function.Function;
+import org.apache.zest.api.composite.ModelDescriptor;
+import org.apache.zest.spi.module.ModuleSpi;
+
+/**
+ * TODO
+ */
+public class ModelModule<T extends ModelDescriptor>
+{
+
+    public static Function<ModelModule<?>, String> toStringFunction = item -> item.model()
+                                                                                  .types()
+                                                                                  .iterator()
+                                                                                  .next()
+                                                                                  .getName() + "[" + item.module()
+                                                                                  .name() + "]";
+
+    public static <T extends ModelDescriptor> Function<T, ModelModule<T>> modelModuleFunction( final ModuleSpi module )
+    {
+        return model1 -> new ModelModule<>( module, model1 );
+    }
+
+    public static Function<ModelModule<? extends ModelDescriptor>, ModelDescriptor> modelFunction()
+    {
+        return modelModule -> {
+            return modelModule.model();
+        };
+    }
+
+    private final ModuleSpi module;
+    private final T model;
+
+    public ModelModule( ModuleSpi module, T model )
+    {
+        this.module = module;
+        this.model = model;
+    }
+
+    public ModuleSpi module()
+    {
+        return module;
+    }
+
+    public T model()
+    {
+        return model;
+    }
+
+    @Override
+    public boolean equals( Object o )
+    {
+        if( this == o )
+        {
+            return true;
+        }
+        if( o == null || getClass() != o.getClass() )
+        {
+            return false;
+        }
+
+        ModelModule that = (ModelModule) o;
+
+        //noinspection SimplifiableIfStatement
+        if( model != null ? !model.equals( that.model ) : that.model != null )
+        {
+            return false;
+        }
+
+        return !( module != null ? !module.equals( that.module ) : that.module != null );
+    }
+
+    @Override
+    public int hashCode()
+    {
+        int result = module != null ? module.hashCode() : 0;
+        result = 31 * result + ( model != null ? model.hashCode() : 0 );
+        return result;
+    }
+
+    @Override
+    public String toString()
+    {
+        return module.name() + ":" + model;
+    }
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/spi/src/main/java/org/apache/zest/spi/structure/TypeLookup.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/zest/spi/structure/TypeLookup.java b/core/spi/src/main/java/org/apache/zest/spi/structure/TypeLookup.java
new file mode 100644
index 0000000..94e0473
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/zest/spi/structure/TypeLookup.java
@@ -0,0 +1,125 @@
+/*
+ * 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.zest.spi.structure;
+
+import java.lang.reflect.Type;
+import java.util.List;
+import java.util.stream.Stream;
+import org.apache.zest.api.composite.TransientDescriptor;
+import org.apache.zest.api.entity.EntityDescriptor;
+import org.apache.zest.api.object.ObjectDescriptor;
+import org.apache.zest.api.service.ServiceReference;
+import org.apache.zest.api.value.ValueDescriptor;
+
+public interface TypeLookup
+{
+    /**
+     * Lookup first Entity Model matching the given Type.
+     *
+     * <p>First, if Entity Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Second, if Entity Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * <p><b>Should be used for creational use cases only.</b> For non-creational use cases see
+     * {@link #lookupEntityModels(Class)}.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return First matching Entity Model
+     */
+    ModelModule<EntityDescriptor> lookupEntityModel( Class type );
+
+    /**
+     * Lookup all Entity Models matching the given Type.
+     *
+     * <p>Returned Iterable contains, in order, Entity Models that: </p>
+     *
+     * <ul>
+     * <li>exactly match the given type, in Visibility then Assembly order ;</li>
+     * <li>match a type assignable to the given type, in Visibility then Assembly order.</li>
+     * </ul>
+     *
+     * <p>Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     * <p>Multiple <b>assignable</b> matches are <b>allowed</b> to enable polymorphic fetches and queries.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * <p><b>Should be used for non-creational use cases only.</b> For creational use cases see
+     * {@link #lookupEntityModel(Class)}.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return All matching Entity Models
+     */
+    Iterable<ModelModule<EntityDescriptor>> lookupEntityModels( Class type );
+
+    /**
+     * Lookup first ServiceReference matching the given Type.
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * <p>See {@link #lookupServiceReferences(Type)}.</p>
+     *
+     * @param <T>         Service Type
+     * @param serviceType Looked up Type
+     *
+     * @return First matching ServiceReference
+     */
+    <T> ServiceReference<T> lookupServiceReference( Type serviceType );
+
+    /**
+     * Lookup all ServiceReferences matching the given Type.
+     *
+     * <p>Returned Iterable contains, in order, ServiceReferences that: </p>
+     *
+     * <ul>
+     * <li>exactly match the given type, in Visibility then Assembly order ;</li>
+     * <li>match a type assignable to the given type, in Visibility then Assembly order.</li>
+     * </ul>
+     *
+     * <p>Multiple <b>exact</b> matches with the same Visibility are <b>allowed</b> to enable polymorphic lookup/injection.</p>
+     * <p>Multiple <b>assignable</b> matches with the same Visibility are <b>allowed</b> for the very same reason.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * @param <T>  Service Type
+     * @param type Looked up Type
+     *
+     * @return All matching ServiceReferences
+     */
+    <T> List<ServiceReference<T>> lookupServiceReferences( Type type );
+
+    Stream<Class<?>> allVisibleObjects();
+
+    Stream<ModelModule<ObjectDescriptor>> allObjects();
+
+    Stream<ModelModule<TransientDescriptor>> allTransients();
+
+    Stream<ModelModule<ValueDescriptor>> allValues();
+
+    Stream<ModelModule<EntityDescriptor>> allEntities();
+
+    Stream<ServiceReference<?>> allServices();
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestScenarioTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestScenarioTest.java b/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestScenarioTest.java
index a035345..456c616 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestScenarioTest.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestScenarioTest.java
@@ -14,20 +14,19 @@
 
 package org.apache.zest.test;
 
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
 import org.apache.zest.api.ZestAPI;
 import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.ApplicationDescriptor;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.bootstrap.ApplicationAssembler;
-import org.apache.zest.bootstrap.ApplicationAssembly;
-import org.apache.zest.bootstrap.ApplicationAssemblyFactory;
 import org.apache.zest.bootstrap.Assembler;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.Energy4Java;
 import org.apache.zest.spi.ZestSPI;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
 
 /**
  * Base class for Zest scenario tests. This will create one Zest application per class instead of per test.
@@ -45,6 +44,7 @@ public abstract class AbstractZestScenarioTest
     static protected Module module;
 
     static protected Assembler assembler; // Initialize this in static block of subclass
+    private static UnitOfWorkFactory uowf;
 
     @BeforeClass
     public static void setUp()
@@ -64,6 +64,7 @@ public abstract class AbstractZestScenarioTest
 
         // Assume only one module
         module = application.findModule( "Layer 1", "Module 1" );
+        uowf = module.unitOfWorkFactory();
     }
 
     static protected ApplicationDescriptor newApplication()
@@ -71,15 +72,7 @@ public abstract class AbstractZestScenarioTest
     {
         final Assembler asm = assembler;
 
-        ApplicationAssembler assembler = new ApplicationAssembler()
-        {
-            @Override
-            public ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
-                throws AssemblyException
-            {
-                return applicationFactory.newApplicationAssembly( asm );
-            }
-        };
+        ApplicationAssembler assembler = applicationFactory -> applicationFactory.newApplicationAssembly( asm );
         try
         {
             return zest.newApplicationModel( assembler );
@@ -116,11 +109,11 @@ public abstract class AbstractZestScenarioTest
     public void tearDown()
         throws Exception
     {
-        if( module != null && module.isUnitOfWorkActive() )
+        if( uowf != null && uowf.isUnitOfWorkActive() )
         {
-            while( module.isUnitOfWorkActive() )
+            while( uowf.isUnitOfWorkActive() )
             {
-                UnitOfWork uow = module.currentUnitOfWork();
+                UnitOfWork uow = uowf.currentUnitOfWork();
                 if( uow.isOpen() )
                 {
                     uow.discard();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestTest.java b/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestTest.java
index 8f2fb96..29c27aa 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestTest.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/AbstractZestTest.java
@@ -14,6 +14,9 @@
 
 package org.apache.zest.test;
 
+import org.apache.zest.api.injection.scope.Structure;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.apache.zest.api.unitofwork.UnitOfWork;
@@ -30,6 +33,9 @@ import org.apache.zest.spi.module.ModuleSpi;
 public abstract class AbstractZestTest extends AbstractZestBaseTest
     implements Assembler
 {
+    @Structure
+    protected UnitOfWorkFactory uowf;
+
     protected ModuleSpi module;
 
     @Before
@@ -52,6 +58,7 @@ public abstract class AbstractZestTest extends AbstractZestBaseTest
     {
         LayerAssembly layer = applicationAssembly.layer( "Layer 1" );
         ModuleAssembly module = layer.module( "Module 1" );
+        new DefaultUnitOfWorkAssembler().assemble( module );
         module.objects( AbstractZestTest.this.getClass() );
         assemble( module );
     }
@@ -61,11 +68,11 @@ public abstract class AbstractZestTest extends AbstractZestBaseTest
     public void tearDown()
         throws Exception
     {
-        if( module != null && module.isUnitOfWorkActive() )
+        if( uowf != null && uowf.isUnitOfWorkActive() )
         {
-            while( module.isUnitOfWorkActive() )
+            while( uowf.isUnitOfWorkActive() )
             {
-                UnitOfWork uow = module.currentUnitOfWork();
+                UnitOfWork uow = uowf.currentUnitOfWork();
                 if( uow.isOpen() )
                 {
                     System.err.println( "UnitOfWork not cleaned up:" + uow.usecase().name() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/cache/AbstractCachePoolTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/cache/AbstractCachePoolTest.java b/core/testsupport/src/main/java/org/apache/zest/test/cache/AbstractCachePoolTest.java
index ab05212..e697375 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/cache/AbstractCachePoolTest.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/cache/AbstractCachePoolTest.java
@@ -121,5 +121,4 @@ public abstract class AbstractCachePoolTest
         cache = cachePool.fetchCache( "1", String.class );
         assertNull( "Value not missing", cache.get( "Habba" ) );
     }
-
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/entity/AbstractEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/entity/AbstractEntityStoreTest.java b/core/testsupport/src/main/java/org/apache/zest/test/entity/AbstractEntityStoreTest.java
index af74176..de6956d 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/entity/AbstractEntityStoreTest.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/entity/AbstractEntityStoreTest.java
@@ -155,14 +155,14 @@ public abstract class AbstractEntityStoreTest
     public void whenNewEntityThenCanFindEntityAndCorrectValues()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             TestEntity instance = createEntity( unitOfWork );
             unitOfWork.complete();
 
             // Find entity
-            unitOfWork = module.newUnitOfWork();
+            unitOfWork = uowf.newUnitOfWork();
             instance = unitOfWork.get( instance );
 
             // Check state
@@ -276,19 +276,19 @@ public abstract class AbstractEntityStoreTest
     public void whenRemovedEntityThenCannotFindEntity()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         TestEntity newInstance = createEntity( unitOfWork );
         String identity = newInstance.identity().get();
         unitOfWork.complete();
 
         // Remove entity
-        unitOfWork = module.newUnitOfWork();
+        unitOfWork = uowf.newUnitOfWork();
         TestEntity instance = unitOfWork.get( newInstance );
         unitOfWork.remove( instance );
         unitOfWork.complete();
 
         // Find entity
-        unitOfWork = module.newUnitOfWork();
+        unitOfWork = uowf.newUnitOfWork();
         try
         {
             unitOfWork.get( TestEntity.class, identity );
@@ -311,21 +311,21 @@ public abstract class AbstractEntityStoreTest
         TestEntity testEntity;
         String version;
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder( TestEntity.class );
 
             testEntity = builder.newInstance();
             unitOfWork.complete();
         }
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             testEntity = unitOfWork.get( testEntity );
             version = spi.entityStateOf( testEntity ).version();
 
             unitOfWork.complete();
         }
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             testEntity = unitOfWork.get( testEntity );
             String newVersion = spi.entityStateOf( testEntity ).version();
             assertThat( "version has not changed", newVersion, equalTo( version ) );
@@ -341,14 +341,14 @@ public abstract class AbstractEntityStoreTest
         TestEntity testEntity;
         String version;
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder( TestEntity.class );
 
             testEntity = builder.newInstance();
             unitOfWork.complete();
         }
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             testEntity = unitOfWork.get( testEntity );
             testEntity.name().set( "Rickard" );
             version = spi.entityStateOf( testEntity ).version();
@@ -356,7 +356,7 @@ public abstract class AbstractEntityStoreTest
             unitOfWork.complete();
         }
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             testEntity = unitOfWork.get( testEntity );
             String newVersion = spi.entityStateOf( testEntity ).version();
             assertThat( "version has changed", newVersion, not( equalTo( version ) ) );
@@ -372,14 +372,14 @@ public abstract class AbstractEntityStoreTest
         TestEntity testEntity;
         String version;
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder( TestEntity.class );
 
             testEntity = builder.newInstance();
             unitOfWork.complete();
         }
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             testEntity = unitOfWork.get( testEntity );
             testEntity.manyAssociation().add( 0, testEntity );
             version = spi.entityStateOf( testEntity ).version();
@@ -387,7 +387,7 @@ public abstract class AbstractEntityStoreTest
             unitOfWork.complete();
         }
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             testEntity = unitOfWork.get( testEntity );
             String newVersion = spi.entityStateOf( testEntity ).version();
             assertThat( "version has changed", newVersion, not( equalTo( version ) ) );
@@ -402,7 +402,7 @@ public abstract class AbstractEntityStoreTest
     {
         TestEntity testEntity;
         {
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder( TestEntity.class );
 
             testEntity = builder.newInstance();
@@ -414,7 +414,7 @@ public abstract class AbstractEntityStoreTest
         String version;
         {
             // Start working with Entity in one UoW
-            unitOfWork1 = module.newUnitOfWork();
+            unitOfWork1 = uowf.newUnitOfWork();
             testEntity1 = unitOfWork1.get( testEntity );
             version = spi.entityStateOf( testEntity1 ).version();
             if( version.isEmpty() )
@@ -427,7 +427,7 @@ public abstract class AbstractEntityStoreTest
         }
         {
             // Start working with same Entity in another UoW, and complete it
-            UnitOfWork unitOfWork = module.newUnitOfWork();
+            UnitOfWork unitOfWork = uowf.newUnitOfWork();
             TestEntity testEntity2 = unitOfWork.get( testEntity );
             assertThat( "version is correct", spi.entityStateOf( testEntity1 ).version(), equalTo( version ) );
             testEntity2.name().set( "B" );
@@ -447,7 +447,7 @@ public abstract class AbstractEntityStoreTest
         }
         {
             // Check values
-            unitOfWork1 = module.newUnitOfWork();
+            unitOfWork1 = uowf.newUnitOfWork();
             testEntity1 = unitOfWork1.get( testEntity );
             assertThat( "property name has not been set", testEntity1.name().get(), equalTo( "B" ) );
             assertThat( "version is incorrect", spi.entityStateOf( testEntity1 ).version(),
@@ -460,19 +460,19 @@ public abstract class AbstractEntityStoreTest
     public void givenEntityStoredLoadedChangedWhenUnitOfWorkDiscardsThenDontStoreState()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             String identity = createEntity( unitOfWork ).identity().get();
             unitOfWork.complete();
 
-            unitOfWork = module.newUnitOfWork();
+            unitOfWork = uowf.newUnitOfWork();
             TestEntity entity = unitOfWork.get( TestEntity.class, identity );
             assertThat( entity.intValue().get(), is( 42 ) );
             entity.intValue().set( 23 );
             unitOfWork.discard();
 
-            unitOfWork = module.newUnitOfWork();
+            unitOfWork = uowf.newUnitOfWork();
             entity = unitOfWork.get( TestEntity.class, identity );
             assertThat( entity.intValue().get(), is( 42 ) );
         }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/AbstractAnyQueryTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/AbstractAnyQueryTest.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/AbstractAnyQueryTest.java
index de7676e..e9c18b5 100755
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/AbstractAnyQueryTest.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/AbstractAnyQueryTest.java
@@ -82,7 +82,7 @@ public class AbstractAnyQueryTest
         super.setUp();
         TestData.populate( module );
 
-        this.unitOfWork = this.module.newUnitOfWork();
+        this.unitOfWork = this.module.unitOfWorkFactory().newUnitOfWork();
     }
 
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/TestData.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/TestData.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/TestData.java
index b07055e..48cd6b5 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/TestData.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/TestData.java
@@ -22,10 +22,6 @@ import java.math.BigDecimal;
 import java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.List;
-import org.apache.zest.test.indexing.model.Dog;
-import org.joda.time.DateTime;
-import org.joda.time.LocalDate;
-import org.joda.time.LocalDateTime;
 import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
@@ -42,6 +38,9 @@ import org.apache.zest.test.indexing.model.Person;
 import org.apache.zest.test.indexing.model.Protocol;
 import org.apache.zest.test.indexing.model.QueryParam;
 import org.apache.zest.test.indexing.model.URL;
+import org.joda.time.DateTime;
+import org.joda.time.LocalDate;
+import org.joda.time.LocalDateTime;
 
 import static org.joda.time.DateTimeZone.UTC;
 
@@ -53,7 +52,7 @@ public class TestData
     public static void populate( Module module )
         throws UnitOfWorkCompletionException
     {
-        try( UnitOfWork unitOfWork = module.newUnitOfWork() )
+        try (UnitOfWork unitOfWork = module.unitOfWorkFactory().newUnitOfWork())
         {
             NameableAssert.clear();
             Domain gaming;
@@ -240,12 +239,6 @@ public class TestData
                 felix.name().set( "Felix" );
                 catBuilder.newInstance();
             }
-            {
-                EntityBuilder<Dog> builder = unitOfWork.newEntityBuilder( Dog.class );
-                Dog snoopy = builder.instance();
-                snoopy.name().set( "Snoopy" );
-                builder.newInstance();
-            }
             unitOfWork.complete();
         }
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/AccountModule.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/AccountModule.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/AccountModule.java
index d398e6f..567056a 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/AccountModule.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/AccountModule.java
@@ -43,6 +43,7 @@ class AccountModule
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         module.entities( Account.class, Domain.class ).visibleIn( Visibility.layer );
         module.values( File.class, Host.class, Port.class, Protocol.class, QueryParam.class, URL.class )
             .visibleIn( Visibility.layer );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/ConfigModule.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/ConfigModule.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/ConfigModule.java
index ecd4939..66cc1c2 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/ConfigModule.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/ConfigModule.java
@@ -35,6 +35,7 @@ class ConfigModule
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.application );
         return module;
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/FamilyModule.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/FamilyModule.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/FamilyModule.java
index 9e24b3f..74562bf 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/FamilyModule.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/FamilyModule.java
@@ -41,6 +41,7 @@ class FamilyModule
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         module.entities( Male.class,
                          Female.class,
                          City.class,

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/PersistenceModule.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/PersistenceModule.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/PersistenceModule.java
index b6ae1e7..b6f785a 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/PersistenceModule.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/PersistenceModule.java
@@ -37,6 +37,7 @@ class PersistenceModule
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
         module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.application );
         return module;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestExecutionModule.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestExecutionModule.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestExecutionModule.java
index bf3fe2b..a21b168 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestExecutionModule.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestExecutionModule.java
@@ -40,6 +40,7 @@ public class TestExecutionModule
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         module.objects( testClass ).visibleIn( Visibility.layer );
         return module;
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite1Module.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite1Module.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite1Module.java
index efcb64b..bd7b015 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite1Module.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite1Module.java
@@ -37,6 +37,7 @@ class TestSuite1Module
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         declareTestCase( module, Suite1Case1.class );
         declareTestCase( module, Suite1Case2.class );
         return module;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite2Module.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite2Module.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite2Module.java
index ac3f655..b7560b6 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite2Module.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite2Module.java
@@ -33,6 +33,7 @@ class TestSuite2Module
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         return module;
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite3Module.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite3Module.java b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite3Module.java
index f93ddf7..163cbbb 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite3Module.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/indexing/layered/assembly/TestSuite3Module.java
@@ -33,6 +33,7 @@ class TestSuite3Module
     public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
         throws AssemblyException
     {
+        module.withDefaultUnitOfWorkFactory();
         return module;
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/testsupport/src/main/java/org/apache/zest/test/value/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/zest/test/value/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/zest/test/value/AbstractValueCompositeSerializationTest.java
index 4920ebd..7ff7406 100644
--- a/core/testsupport/src/main/java/org/apache/zest/test/value/AbstractValueCompositeSerializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/zest/test/value/AbstractValueCompositeSerializationTest.java
@@ -92,7 +92,7 @@ public abstract class AbstractValueCompositeSerializationTest
     public void givenValueCompositeWhenSerializingAndDeserializingExpectEquals()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             SomeValue some = buildSomeValue();
@@ -214,7 +214,7 @@ public abstract class AbstractValueCompositeSerializationTest
 
     private BarEntity buildBarEntity( String cathedral )
     {
-        EntityBuilder<BarEntity> barBuilder = module.currentUnitOfWork().newEntityBuilder( BarEntity.class );
+        EntityBuilder<BarEntity> barBuilder = uowf.currentUnitOfWork().newEntityBuilder( BarEntity.class );
         barBuilder.instance().cathedral().set( cathedral );
         return barBuilder.newInstance();
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java b/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java
index 2c833e0..f34fdd4 100755
--- a/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java
@@ -67,7 +67,7 @@ import org.apache.zest.spi.entitystore.EntityStoreSPI;
 import org.apache.zest.spi.entitystore.EntityStoreUnitOfWork;
 import org.apache.zest.spi.entitystore.StateCommitter;
 import org.apache.zest.spi.entitystore.helpers.DefaultEntityState;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java
index cd8faec..95ce3fe 100755
--- a/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java
@@ -68,7 +68,7 @@ import org.apache.zest.spi.entitystore.helpers.DefaultEntityState;
 import org.apache.zest.spi.entitystore.helpers.JSONKeys;
 import org.apache.zest.spi.entitystore.helpers.Migration;
 import org.apache.zest.spi.entitystore.helpers.StateStore;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
 import org.json.JSONArray;
 import org.json.JSONException;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/DerbySQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/DerbySQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/DerbySQLEntityStoreTest.java
index c47bb9e..c33ddd0 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/DerbySQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/DerbySQLEntityStoreTest.java
@@ -75,7 +75,7 @@ public class DerbySQLEntityStoreTest
     public void tearDown()
         throws Exception
     {
-        UnitOfWork uow = this.module.newUnitOfWork( UsecaseBuilder.newUsecase(
+        UnitOfWork uow = this.uowf.newUnitOfWork( UsecaseBuilder.newUsecase(
             "Delete " + getClass().getSimpleName() + " test data" ) );
         try
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/MySQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/MySQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/MySQLEntityStoreTest.java
index 7788b71..cb263ec 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/MySQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/MySQLEntityStoreTest.java
@@ -86,7 +86,7 @@ public class MySQLEntityStoreTest
         {
             return;
         }
-        UnitOfWork uow = this.module.newUnitOfWork(
+        UnitOfWork uow = this.uowf.newUnitOfWork(
             UsecaseBuilder.newUsecase( "Delete " + getClass().getSimpleName() + " test data" )
         );
         try

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/PostgreSQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/PostgreSQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/PostgreSQLEntityStoreTest.java
index 27e93f5..5504e36 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/PostgreSQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/zest/entitystore/sql/PostgreSQLEntityStoreTest.java
@@ -112,7 +112,7 @@ public class PostgreSQLEntityStoreTest
     public void tearDown()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork(
+        UnitOfWork uow = uowf.newUnitOfWork(
             UsecaseBuilder.newUsecase( "Delete " + getClass().getSimpleName() + " test data" )
         );
         try

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchQueryMultimoduleTest.java b/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchQueryMultimoduleTest.java
index 6e50400..edd2652 100755
--- a/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchQueryMultimoduleTest.java
+++ b/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchQueryMultimoduleTest.java
@@ -25,6 +25,7 @@ import org.apache.zest.api.common.Visibility;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.LayerAssembly;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.index.elasticsearch.assembly.ESFilesystemIndexQueryAssembler;
 import org.apache.zest.library.fileconfig.FileConfigurationOverride;
 import org.apache.zest.library.fileconfig.FileConfigurationService;
@@ -46,6 +47,7 @@ public class ElasticSearchQueryMultimoduleTest extends ElasticSearchQueryTest
 
         module = module.layer().module( "module2" );
         new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( module );
+        new DefaultUnitOfWorkAssembler().assemble( module );
 
         // Config module
         LayerAssembly configLayer = module.layer().application().layer( "config" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchTest.java b/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchTest.java
index f5efe83..6bf8c83 100644
--- a/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchTest.java
+++ b/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ElasticSearchTest.java
@@ -159,7 +159,7 @@ public class ElasticSearchTest
     {
         String title = "Foo Bar Bazar!";
 
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         EntityBuilder<Author> authorBuilder = uow.newEntityBuilder( Author.class );
         Author author = authorBuilder.instance();
@@ -199,7 +199,7 @@ public class ElasticSearchTest
 
         uow.complete();
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
 
         QueryBuilder<Post> queryBuilder = module.newQueryBuilder( Post.class );
         Query<Post> query = uow.newQuery( queryBuilder );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ImmenseTermTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ImmenseTermTest.java b/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ImmenseTermTest.java
index 9947de2..b6b41f1 100644
--- a/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ImmenseTermTest.java
+++ b/extensions/indexing-elasticsearch/src/test/java/org/apache/zest/index/elasticsearch/ImmenseTermTest.java
@@ -117,18 +117,18 @@ public class ImmenseTermTest
     {
         long count = 10_000L;
         TestEntity testEntity;
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             testEntity = uow.newEntity( TestEntity.class );
             for( long i = 0; i < count; i++ )
             {
-                TestEntity2 testEntity2 = module.currentUnitOfWork().newEntity( TestEntity2.class );
+                TestEntity2 testEntity2 = uowf.currentUnitOfWork().newEntity( TestEntity2.class );
                 testEntity2.property().set( "test" );
                 testEntity.manyAssociation().add( testEntity2 );
             }
             uow.complete();
         }
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             testEntity = uow.get( testEntity );
             Query<TestEntity2> query = uow.newQuery(

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsAllTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsAllTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsAllTest.java
index 5a166c8..c0092a1 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsAllTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsAllTest.java
@@ -312,7 +312,7 @@ public class ContainsAllTest
         builder = builder.where( QueryExpressions.containsAll(
                 QueryExpressions.templateFor( ExampleEntity.class ).strings(),
                 Iterables.iterable( strings ) ) );
-        return this.module.currentUnitOfWork().newQuery( builder ).find();
+        return this.uowf.currentUnitOfWork().newQuery( builder ).find();
     }
 
     private ExampleEntity findEntityBasedOnValueStrings( String... valueStrings )
@@ -340,18 +340,18 @@ public class ContainsAllTest
         )
         );
 
-        return this.module.currentUnitOfWork().newQuery( builder );
+        return this.uowf.currentUnitOfWork().newQuery( builder );
     }
 
     private ExampleEntity performContainsAllStringsTest( Set<String> entityStrings, Set<String> queryableStrings )
         throws Exception
     {
-        UnitOfWork creatingUOW = this.module.newUnitOfWork();
+        UnitOfWork creatingUOW = this.uowf.newUnitOfWork();
         String[] entityStringsArray = new String[entityStrings.size()];
         createEntityWithStrings( creatingUOW, this.module, entityStrings.toArray( entityStringsArray ) );
         creatingUOW.complete();
 
-        UnitOfWork queryingUOW = this.module.newUnitOfWork();
+        UnitOfWork queryingUOW = this.uowf.newUnitOfWork();
         try
         {
             String[] queryableStringsArray = new String[queryableStrings.size()];
@@ -367,12 +367,12 @@ public class ContainsAllTest
     private ExampleEntity performContainsAllStringValueTest( Set<String> entityStrings, Set<String> queryableStrings )
         throws Exception
     {
-        UnitOfWork creatingUOW = this.module.newUnitOfWork();
+        UnitOfWork creatingUOW = this.uowf.newUnitOfWork();
         String[] entityStringsArray = new String[entityStrings.size()];
         createEntityWithComplexValues( creatingUOW, this.module, entityStrings.toArray( entityStringsArray ) );
         creatingUOW.complete();
 
-        UnitOfWork queryingUOW = this.module.newUnitOfWork();
+        UnitOfWork queryingUOW = this.uowf.newUnitOfWork();
         try
         {
             String[] queryableStringsArray = new String[queryableStrings.size()];

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsTest.java
index 3d0ab4a..9fd4e54 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/ContainsTest.java
@@ -143,7 +143,7 @@ public class ContainsTest extends AbstractZestTest
             string
             )
       );
-      return this.module.currentUnitOfWork().newQuery( builder ).find();
+      return this.uowf.currentUnitOfWork().newQuery( builder ).find();
 
    }
 
@@ -167,17 +167,17 @@ public class ContainsTest extends AbstractZestTest
             )
          );
 
-      return this.module.currentUnitOfWork().newQuery( builder);
+      return this.uowf.currentUnitOfWork().newQuery( builder);
    }
 
    private ExampleEntity performContainsStringTest(Set<String> entityStrings, String queryableString) throws Exception
    {
-      UnitOfWork creatingUOW = this.module.newUnitOfWork();
+      UnitOfWork creatingUOW = this.uowf.newUnitOfWork();
       String[] entityStringsArray = new String[entityStrings.size()];
       ContainsAllTest.createEntityWithStrings(creatingUOW, this.module, entityStrings.toArray(entityStringsArray));
       creatingUOW.complete();
 
-      UnitOfWork queryingUOW = this.module.newUnitOfWork();
+      UnitOfWork queryingUOW = this.uowf.newUnitOfWork();
       try
       {
          ExampleEntity entity = this.findEntity(queryableString);
@@ -191,12 +191,12 @@ public class ContainsTest extends AbstractZestTest
 
    private ExampleEntity performContainsStringValueTest(Set<String> entityStrings, String queryableString) throws Exception
    {
-      UnitOfWork creatingUOW = this.module.newUnitOfWork();
+      UnitOfWork creatingUOW = this.uowf.newUnitOfWork();
       String[] entityStringsArray = new String[entityStrings.size()];
       ContainsAllTest.createEntityWithComplexValues(creatingUOW, this.module, entityStrings.toArray(entityStringsArray));
       creatingUOW.complete();
 
-      UnitOfWork queryingUOW = this.module.newUnitOfWork();
+      UnitOfWork queryingUOW = this.uowf.newUnitOfWork();
       try
       {
          ExampleEntity entity = this.findEntityBasedOnValueString(queryableString);

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/MultiLayeredTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/MultiLayeredTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/MultiLayeredTest.java
index 7923b75..cd8aeae 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/MultiLayeredTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/MultiLayeredTest.java
@@ -42,7 +42,8 @@ public class MultiLayeredTest extends AbstractMultiLayeredIndexingTest
         public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
             throws AssemblyException
         {
-            new RdfMemoryStoreAssembler( Visibility.layer, Visibility.module ).assemble( module );
+            module.withDefaultUnitOfWorkFactory();
+            new RdfMemoryStoreAssembler( Visibility.application, Visibility.module ).assemble( module );
             return module;
         }
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RDFPerformanceTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RDFPerformanceTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RDFPerformanceTest.java
index f051935..c005360 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RDFPerformanceTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RDFPerformanceTest.java
@@ -89,7 +89,7 @@ public class RDFPerformanceTest extends AbstractZestTest
         List<ExampleEntity> entities = new ArrayList<ExampleEntity>();
         for (Integer x = 0; x < howMany; ++x)
         {
-            ExampleEntity exampleEntity = this.module.currentUnitOfWork().newEntity( ExampleEntity.class, "entity" + x );
+            ExampleEntity exampleEntity = this.uowf.currentUnitOfWork().newEntity( ExampleEntity.class, "entity" + x );
 
             for (ExampleEntity entity : entities)
             {
@@ -110,14 +110,14 @@ public class RDFPerformanceTest extends AbstractZestTest
     {
         for (ExampleEntity entity : entities)
         {
-            this.module.currentUnitOfWork().remove( this.module.currentUnitOfWork().get( entity ) );
+            this.uowf.currentUnitOfWork().remove( this.uowf.currentUnitOfWork().get( entity ) );
         }
     }
 
     private List<ExampleEntity> doList( int howMany )
     {
         List<ExampleEntity> list = new ArrayList<ExampleEntity>();
-        UnitOfWork uow = this.module.newUnitOfWork();
+        UnitOfWork uow = this.uowf.newUnitOfWork();
         Iterator<ExampleEntity> iter = uow.newQuery( this.module.newQueryBuilder( ExampleEntity.class ) ).iterator();
         int found = 0;
         while (iter.hasNext())
@@ -141,11 +141,11 @@ public class RDFPerformanceTest extends AbstractZestTest
 
     private void doRemove( int howMany )
     {
-        Iterator<ExampleEntity> iter = this.module.currentUnitOfWork().newQuery( this.module.newQueryBuilder( ExampleEntity.class )).maxResults( howMany ).iterator();
+        Iterator<ExampleEntity> iter = this.uowf.currentUnitOfWork().newQuery( this.module.newQueryBuilder( ExampleEntity.class )).maxResults( howMany ).iterator();
         Integer removed = 0;
         while (iter.hasNext())
         {
-            this.module.currentUnitOfWork().remove( iter.next() );
+            this.uowf.currentUnitOfWork().remove( iter.next() );
             ++removed;
         }
 
@@ -159,7 +159,7 @@ public class RDFPerformanceTest extends AbstractZestTest
     {
         long startTest = System.currentTimeMillis();
 
-        UnitOfWork creatingUOW = this.module.newUnitOfWork();
+        UnitOfWork creatingUOW = this.uowf.newUnitOfWork();
         Long startingTime = System.currentTimeMillis();
         List<ExampleEntity> entities = this.doCreate( howMany );
         LOG.info( "Time to create " + howMany + " entities (ms): " + (System.currentTimeMillis() - startingTime) );
@@ -172,7 +172,7 @@ public class RDFPerformanceTest extends AbstractZestTest
         List<ExampleEntity> entityList = this.doList( howMany );
 
         startingTime = System.currentTimeMillis();
-        UnitOfWork uow = this.module.newUnitOfWork();
+        UnitOfWork uow = this.uowf.newUnitOfWork();
         for (int i = 0; i < 1000; i++)
         {
             Query<ExampleEntity> query = uow.newQuery( this.module.newQueryBuilder( ExampleEntity.class ).
@@ -183,7 +183,7 @@ public class RDFPerformanceTest extends AbstractZestTest
         long endTest = System.currentTimeMillis();
         LOG.info( "Time to query " + howMany + " entities (ms): " + (endTest - startingTime) );
 
-        UnitOfWork deletingUOW = this.module.newUnitOfWork();
+        UnitOfWork deletingUOW = this.uowf.newUnitOfWork();
         startingTime = System.currentTimeMillis();
         this.doRemoveAll( entityList );
 //      this.doRemove(200);

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfNamedQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfNamedQueryMultimoduleTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfNamedQueryMultimoduleTest.java
index d0b1d19..e1434f9 100755
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfNamedQueryMultimoduleTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfNamedQueryMultimoduleTest.java
@@ -24,6 +24,7 @@ import org.apache.zest.api.common.Visibility;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.LayerAssembly;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.index.rdf.assembly.RdfMemoryStoreAssembler;
 import org.apache.zest.test.EntityTestAssembler;
 
@@ -39,10 +40,12 @@ public class RdfNamedQueryMultimoduleTest
         assembleValues( module, Visibility.module );
 
         ModuleAssembly storeModule = layer.module( "store" );
+        new DefaultUnitOfWorkAssembler().assemble( storeModule );
         new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( storeModule );
         assembleValues( storeModule, Visibility.module );
 
         ModuleAssembly indexModule = layer.module( "index" );
+        new DefaultUnitOfWorkAssembler().assemble( indexModule );
         new RdfMemoryStoreAssembler( Visibility.layer, Visibility.module ).assemble( indexModule );
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryMultimoduleTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryMultimoduleTest.java
index d25f79a..390818e 100755
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryMultimoduleTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryMultimoduleTest.java
@@ -25,6 +25,7 @@ import org.apache.zest.api.common.Visibility;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.LayerAssembly;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.index.rdf.assembly.RdfNativeSesameStoreAssembler;
 import org.apache.zest.library.rdf.repository.NativeConfiguration;
 import org.apache.zest.test.EntityTestAssembler;
@@ -49,9 +50,11 @@ public class RdfQueryMultimoduleTest
         ModuleAssembly storeModule = layer.module( "store" );
         new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( storeModule );
         assembleValues( storeModule, Visibility.module );
+        new DefaultUnitOfWorkAssembler().assemble( storeModule );
 
         ModuleAssembly indexModule = layer.module( "index" );
         new RdfNativeSesameStoreAssembler( Visibility.layer, Visibility.module ).assemble( indexModule );
+        new DefaultUnitOfWorkAssembler().assemble( indexModule );
 
         LayerAssembly configLayer = module.layer().application().layer( "config" );
         module.layer().uses( configLayer );
@@ -59,6 +62,7 @@ public class RdfQueryMultimoduleTest
         config.entities( NativeConfiguration.class ).visibleIn( Visibility.application );
         config.forMixin( NativeConfiguration.class ).declareDefaults().dataDirectory().set( DATA_DIR.getAbsolutePath() );
         new EntityTestAssembler().assemble( config );
+        new DefaultUnitOfWorkAssembler().assemble( config );
     }
 
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryTest.java
index 867a3a4..4469b75 100755
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/RdfQueryTest.java
@@ -22,6 +22,7 @@ import java.io.File;
 import org.apache.zest.api.common.Visibility;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.index.rdf.assembly.RdfNativeSesameStoreAssembler;
 import org.apache.zest.library.rdf.repository.NativeConfiguration;
 import org.apache.zest.spi.query.EntityFinderException;
@@ -51,6 +52,7 @@ public class RdfQueryTest
         config.entities( NativeConfiguration.class ).visibleIn( Visibility.layer );
         config.forMixin( NativeConfiguration.class ).declareDefaults().dataDirectory().set( DATA_DIR.getAbsolutePath() );
         new EntityTestAssembler().assemble( config );
+        new DefaultUnitOfWorkAssembler().assemble( config );
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi173/Qi173IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi173/Qi173IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi173/Qi173IssueTest.java
index 009a5cd..1d83240 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi173/Qi173IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi173/Qi173IssueTest.java
@@ -52,7 +52,7 @@ public class Qi173IssueTest
     @Test
     public void testPersistence()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             createCar( "Volvo", "S80", 2007 );
@@ -73,7 +73,7 @@ public class Qi173IssueTest
             e.printStackTrace();
         }
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
         QueryBuilder<Car> qb = module.newQueryBuilder( Car.class );
         Car template = QueryExpressions.templateFor( Car.class );
         qb = qb.where( QueryExpressions.eq( template.year(), 2007 ) );
@@ -104,7 +104,7 @@ public class Qi173IssueTest
 
     private String createCar( String manufacturer, String model, int year )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<Car> builder = uow.newEntityBuilder( Car.class );
         Car prototype = builder.instanceFor( Car.class );
         prototype.manufacturer().set( manufacturer );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/AbstractIssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/AbstractIssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/AbstractIssueTest.java
index f09d95c..b9402ec 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/AbstractIssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/AbstractIssueTest.java
@@ -41,7 +41,7 @@ public abstract class AbstractIssueTest
     protected final String newZestAccount()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         EntityBuilder<AccountComposite> entityBuilder = work.newEntityBuilder( AccountComposite.class );
         AccountComposite accountComposite = entityBuilder.instance();
         accountComposite.name().set( DEFAULT_ACCOUNT_NAME );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationMandatory/IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationMandatory/IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationMandatory/IssueTest.java
index f39421d..ed7c460 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationMandatory/IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationMandatory/IssueTest.java
@@ -53,7 +53,7 @@ public final class IssueTest
         String id = newZestAccount();
 
         // Make sure there's no unit of work
-        assertNull( module.currentUnitOfWork() );
+        assertNull( uowf.currentUnitOfWork() );
 
         accountService.getAccountById( id );
     }
@@ -66,14 +66,14 @@ public final class IssueTest
         String id = newZestAccount();
 
         // Make sure there's no unit of work
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
 
-        UnitOfWork parentUnitOfWork = module.newUnitOfWork();
+        UnitOfWork parentUnitOfWork = uowf.newUnitOfWork();
 
         AccountComposite account = accountService.getAccountById( id );
         assertNotNull( account );
 
-        UnitOfWork currentUnitOfWork = module.currentUnitOfWork();
+        UnitOfWork currentUnitOfWork = uowf.currentUnitOfWork();
         assertEquals( parentUnitOfWork, currentUnitOfWork );
 
         assertTrue( currentUnitOfWork.isOpen() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequired/IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequired/IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequired/IssueTest.java
index 40f692a..23a1d8b 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequired/IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequired/IssueTest.java
@@ -49,12 +49,12 @@ public final class IssueTest
         String id = newZestAccount();
 
         // Make sure there's no unit of work
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
 
         AccountComposite account = accountService.getAccountById( id );
         assertNotNull( account );
 
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
     }
 
     @Test
@@ -65,14 +65,14 @@ public final class IssueTest
         String id = newZestAccount();
 
         // Make sure there's no unit of work
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
 
-        UnitOfWork parentUnitOfWork = module.newUnitOfWork();
+        UnitOfWork parentUnitOfWork = uowf.newUnitOfWork();
 
         AccountComposite account = accountService.getAccountById( id );
         assertNotNull( account );
 
-        UnitOfWork currentUnitOfWork = module.currentUnitOfWork();
+        UnitOfWork currentUnitOfWork = uowf.currentUnitOfWork();
         assertEquals( parentUnitOfWork, currentUnitOfWork );
 
         assertTrue( currentUnitOfWork.isOpen() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequiresNew/IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequiresNew/IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequiresNew/IssueTest.java
index 18dc869..1675973 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequiresNew/IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi64/withPropagationRequiresNew/IssueTest.java
@@ -49,12 +49,12 @@ public class IssueTest
         String id = newZestAccount();
 
         // Make sure there's no unit of work
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
 
         AccountComposite account = accountService.getAccountById( id );
         assertNotNull( account );
 
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
     }
 
     @Test
@@ -65,14 +65,14 @@ public class IssueTest
         String id = newZestAccount();
 
         // Make sure there's no unit of work
-        assertFalse( module.isUnitOfWorkActive() );
+        assertFalse( uowf.isUnitOfWorkActive() );
 
-        UnitOfWork parentUnitOfWork = module.newUnitOfWork();
+        UnitOfWork parentUnitOfWork = uowf.newUnitOfWork();
 
         AccountComposite account = accountService.getAccountById( id );
         assertNotNull( account );
 
-        UnitOfWork currentUnitOfWork = module.currentUnitOfWork();
+        UnitOfWork currentUnitOfWork = uowf.currentUnitOfWork();
         assertEquals( parentUnitOfWork, currentUnitOfWork );
 
         assertTrue( currentUnitOfWork.isOpen() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi66/Qi66IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi66/Qi66IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi66/Qi66IssueTest.java
index f655b32..6904c24 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi66/Qi66IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/zest/index/rdf/qi66/Qi66IssueTest.java
@@ -49,7 +49,7 @@ public class Qi66IssueTest
     {
         String accountIdentity = newZestAccount();
 
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         AccountComposite account = work.get( AccountComposite.class, accountIdentity );
         assertNotNull( account );
 
@@ -74,7 +74,7 @@ public class Qi66IssueTest
     private String newZestAccount()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         EntityBuilder<AccountComposite> entityBuilder = work.newEntityBuilder( AccountComposite.class );
         AccountComposite accountComposite = entityBuilder.instance();
         accountComposite.name().set( ACCOUNT_NAME );


[6/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityVisibilityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityVisibilityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityVisibilityTest.java
index 77baf16..0d0e6f1 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityVisibilityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/EntityVisibilityTest.java
@@ -16,6 +16,8 @@
 
 package org.apache.zest.runtime.entity;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -43,6 +45,7 @@ public class EntityVisibilityTest
     private Energy4Java zest;
     private Module module;
     private Application app;
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void setup()
@@ -76,6 +79,7 @@ public class EntityVisibilityTest
         } );
         app.activate();
         module = app.findModule( "From Layer", "From" );
+        uowf = module.unitOfWorkFactory();
     }
 
     @After
@@ -172,7 +176,7 @@ public class EntityVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -190,7 +194,7 @@ public class EntityVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -208,7 +212,7 @@ public class EntityVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleModuleVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -226,7 +230,7 @@ public class EntityVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -244,7 +248,7 @@ public class EntityVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -262,7 +266,7 @@ public class EntityVisibilityTest
     @Test( expected = EntityTypeNotFoundException.class )
     public void givenFromEntityWhenAccessingBesideModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -280,7 +284,7 @@ public class EntityVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBelowApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -298,7 +302,7 @@ public class EntityVisibilityTest
     @Test( expected = EntityTypeNotFoundException.class )
     public void givenFromEntityWhenAccessingBelowLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -316,7 +320,7 @@ public class EntityVisibilityTest
     @Test( expected = EntityTypeNotFoundException.class )
     public void givenFromEntityWhenAccessingBelowModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -334,7 +338,7 @@ public class EntityVisibilityTest
     @Test( expected = EntityTypeNotFoundException.class )
     public void givenFromEntityWhenAccessingAboveApplicationVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -352,7 +356,7 @@ public class EntityVisibilityTest
     @Test( expected = EntityTypeNotFoundException.class )
     public void givenFromEntityWhenAccessingAboveLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -370,7 +374,7 @@ public class EntityVisibilityTest
     @Test( expected = EntityTypeNotFoundException.class )
     public void givenFromEntityWhenAccessingAboveModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -655,6 +659,7 @@ public class EntityVisibilityTest
             module.entities( ModuleApplicationVisible.class ).visibleIn( Visibility.application );
             module.entities( ModuleLayerVisible.class ).visibleIn( Visibility.layer );
             module.entities( ModuleModuleVisible.class ).visibleIn( Visibility.module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -672,6 +677,7 @@ public class EntityVisibilityTest
             module.entities( BelowModuleVisible.class ).visibleIn( Visibility.module );
 
             new EntityTestAssembler().visibleIn( Visibility.application ).assemble( module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -687,6 +693,7 @@ public class EntityVisibilityTest
             module.entities( AboveApplicationVisible.class ).visibleIn( Visibility.application );
             module.entities( AboveLayerVisible.class ).visibleIn( Visibility.layer );
             module.entities( AboveModuleVisible.class ).visibleIn( Visibility.module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -701,6 +708,7 @@ public class EntityVisibilityTest
             module.entities( BesideApplicationVisible.class ).visibleIn( Visibility.application );
             module.entities( BesideLayerVisible.class ).visibleIn( Visibility.layer );
             module.entities( BesideModuleVisible.class ).visibleIn( Visibility.module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -756,12 +764,12 @@ public class EntityVisibilityTest
         implements From
     {
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Override
         public void moduleApplicationVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 ModuleApplicationVisible entity = uow.newEntity( ModuleApplicationVisible.class );
@@ -778,7 +786,7 @@ public class EntityVisibilityTest
         @Override
         public void moduleLayerVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 ModuleLayerVisible entity = uow.newEntity( ModuleLayerVisible.class );
@@ -795,7 +803,7 @@ public class EntityVisibilityTest
         @Override
         public void moduleModuleVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 ModuleModuleVisible entity = uow.newEntity( ModuleModuleVisible.class );
@@ -812,7 +820,7 @@ public class EntityVisibilityTest
         @Override
         public void besideApplicationVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 BesideApplicationVisible entity = uow.newEntity( BesideApplicationVisible.class );
@@ -829,7 +837,7 @@ public class EntityVisibilityTest
         @Override
         public void besideLayerVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 BesideLayerVisible entity = uow.newEntity( BesideLayerVisible.class );
@@ -846,7 +854,7 @@ public class EntityVisibilityTest
         @Override
         public void besideModuleVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 BesideModuleVisible entity = uow.newEntity( BesideModuleVisible.class );
@@ -863,7 +871,7 @@ public class EntityVisibilityTest
         @Override
         public void belowApplicationVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 BelowApplicationVisible entity = uow.newEntity( BelowApplicationVisible.class );
@@ -880,7 +888,7 @@ public class EntityVisibilityTest
         @Override
         public void belowLayerVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 BelowLayerVisible entity = uow.newEntity( BelowLayerVisible.class );
@@ -897,7 +905,7 @@ public class EntityVisibilityTest
         @Override
         public void belowModuleVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 BelowModuleVisible entity = uow.newEntity( BelowModuleVisible.class );
@@ -914,7 +922,7 @@ public class EntityVisibilityTest
         @Override
         public void aboveApplicationVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 AboveApplicationVisible entity = uow.newEntity( AboveApplicationVisible.class );
@@ -931,7 +939,7 @@ public class EntityVisibilityTest
         @Override
         public void aboveLayerVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 AboveLayerVisible entity = uow.newEntity( AboveLayerVisible.class );
@@ -948,7 +956,7 @@ public class EntityVisibilityTest
         @Override
         public void aboveModuleVisible()
         {
-            UnitOfWork uow = module.newUnitOfWork();
+            UnitOfWork uow = uowf.newUnitOfWork();
             try
             {
                 AboveModuleVisible entity = uow.newEntity( AboveModuleVisible.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/LifecycleTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/LifecycleTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/LifecycleTest.java
index 495bff8..e2b132c 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/LifecycleTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/LifecycleTest.java
@@ -51,7 +51,7 @@ public class LifecycleTest
     public void whenEntityHasLifecycleWhenInstantiatedThenInvokeCreate()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder( TestEntity.class );
@@ -70,7 +70,7 @@ public class LifecycleTest
     public void whenEntityHasLifecycleWhenRemovedThenInvokeRemove()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder( TestEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/AssociationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/AssociationTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/AssociationTest.java
index a1627d7..8261004 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/AssociationTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/AssociationTest.java
@@ -52,7 +52,7 @@ public class AssociationTest
     @Test
     public void testAssociation()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
 
         try
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/ImmutableAssociationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/ImmutableAssociationTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/ImmutableAssociationTest.java
index 3dd855b..ad64912 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/ImmutableAssociationTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/entity/associations/ImmutableAssociationTest.java
@@ -44,7 +44,7 @@ public class ImmutableAssociationTest
     public void givenEntityWithImmutableAssociationWhenBuildingThenNoException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             PersonEntity father = unitOfWork.newEntity( PersonEntity.class );
@@ -64,7 +64,7 @@ public class ImmutableAssociationTest
     public void givenEntityWithImmutableAssociationWhenChangingValueThenThrowException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder( PersonEntity.class );
@@ -89,7 +89,7 @@ public class ImmutableAssociationTest
     public void givenEntityWithImmutableManyAssociationWhenBuildingThenNoException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder( PersonEntity.class );
@@ -111,7 +111,7 @@ public class ImmutableAssociationTest
     public void givenEntityWithImmutableManyAssociationWhenChangingValueThenThrowException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder( PersonEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/injection/ConstructorInjectionOfThisTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/injection/ConstructorInjectionOfThisTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/injection/ConstructorInjectionOfThisTest.java
index 43ae9cb..be703e6 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/injection/ConstructorInjectionOfThisTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/injection/ConstructorInjectionOfThisTest.java
@@ -15,6 +15,7 @@
  */
 package org.apache.zest.runtime.injection;
 
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
 import org.apache.zest.api.common.UseDefaults;
@@ -49,6 +50,7 @@ public class ConstructorInjectionOfThisTest
                 throws AssemblyException
             {
                 module.values( Does.class ).withMixins( DoesMixin.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
         Module module = singletonAssembler.application().findModule( "Layer 1", "Module 1" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/injection/UnitOfWorkInjectionTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/injection/UnitOfWorkInjectionTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/injection/UnitOfWorkInjectionTest.java
index 7c3d2f0..93ba516 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/injection/UnitOfWorkInjectionTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/injection/UnitOfWorkInjectionTest.java
@@ -47,15 +47,15 @@ public class UnitOfWorkInjectionTest
         throws Exception
     {
         Usecase usecase = UsecaseBuilder.newUsecase( "usecase1" );
-        UnitOfWork uow = module.newUnitOfWork( usecase );
+        UnitOfWork uow = uowf.newUnitOfWork( usecase );
         try
         {
             Trial trial = uow.newEntity( Trial.class, "123" );
             trial.doSomething();
             uow.complete();
-            uow = module.newUnitOfWork( usecase );
+            uow = uowf.newUnitOfWork( usecase );
             usecase = UsecaseBuilder.newUsecase( "usecase2" );
-            UnitOfWork uow2 = module.newUnitOfWork( usecase );
+            UnitOfWork uow2 = uowf.newUnitOfWork( usecase );
             trial = uow.get( trial );
             trial.doSomething();
             assertEquals( "123", ( (EntityComposite) trial ).identity().get() );
@@ -70,9 +70,9 @@ public class UnitOfWorkInjectionTest
         {
             try
             {
-                while( module.isUnitOfWorkActive() )
+                while( uowf.isUnitOfWorkActive() )
                 {
-                    uow = module.currentUnitOfWork();
+                    uow = uowf.currentUnitOfWork();
                     uow.discard();
                 }
             }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/instantiation/TransientInstantiationTests.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/instantiation/TransientInstantiationTests.java b/core/runtime/src/test/java/org/apache/zest/runtime/instantiation/TransientInstantiationTests.java
index bbb0197..bea66f9 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/instantiation/TransientInstantiationTests.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/instantiation/TransientInstantiationTests.java
@@ -58,7 +58,6 @@ public class TransientInstantiationTests
     public static class MyMixin
         implements My
     {
-
         public String doSomething()
         {
             return "Niclas";

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyMixinTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyMixinTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyMixinTest.java
index d00f655..d3ec351 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyMixinTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyMixinTest.java
@@ -54,11 +54,11 @@ public class AssemblyMixinTest
     public void testAssemblyMixinsEntity()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         FooEntity entity = uow.newEntity( FooEntity.class, "123" );
         uow.complete();
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
         Foo foo = uow.get( Foo.class, "123" );
 
         try

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyRoleTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyRoleTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyRoleTest.java
index f8fb6a2..80efede 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyRoleTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/mixin/AssemblyRoleTest.java
@@ -63,11 +63,11 @@ public class AssemblyRoleTest
     public void testAssemblyMixinsEntity()
         throws UnitOfWorkCompletionException
     {
-        UnitOfWork uow = module.newUnitOfWork();
-        FooEntity entity = uow.newEntity( FooEntity.class, "123" );
+        UnitOfWork uow = uowf.newUnitOfWork();
+        uow.newEntity( FooEntity.class, "123" );
         uow.complete();
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
         Foo foo = uow.get( Foo.class, "123" );
 
         try

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/objects/ObjectVisibilityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/objects/ObjectVisibilityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/objects/ObjectVisibilityTest.java
index 22a733b..dcaa0c8 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/objects/ObjectVisibilityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/objects/ObjectVisibilityTest.java
@@ -16,6 +16,8 @@
 
 package org.apache.zest.runtime.objects;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -42,6 +44,7 @@ public class ObjectVisibilityTest
 
     private Energy4Java zest;
     private Module module;
+    private UnitOfWorkFactory uowf;
     private Application app;
 
     @Before
@@ -76,6 +79,7 @@ public class ObjectVisibilityTest
         } );
         app.activate();
         module = app.findModule( "From Layer", "From" );
+        uowf = module.unitOfWorkFactory();
     }
 
     @After
@@ -172,7 +176,7 @@ public class ObjectVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -190,7 +194,7 @@ public class ObjectVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -208,7 +212,7 @@ public class ObjectVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleModuleVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -226,7 +230,7 @@ public class ObjectVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -244,7 +248,7 @@ public class ObjectVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -262,7 +266,7 @@ public class ObjectVisibilityTest
     @Test( expected = NoSuchObjectException.class )
     public void givenFromEntityWhenAccessingBesideModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -280,7 +284,7 @@ public class ObjectVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBelowApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -298,7 +302,7 @@ public class ObjectVisibilityTest
     @Test( expected = NoSuchObjectException.class )
     public void givenFromEntityWhenAccessingBelowLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -316,7 +320,7 @@ public class ObjectVisibilityTest
     @Test( expected = NoSuchObjectException.class )
     public void givenFromEntityWhenAccessingBelowModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -334,7 +338,7 @@ public class ObjectVisibilityTest
     @Test( expected = NoSuchObjectException.class )
     public void givenFromEntityWhenAccessingAboveApplicationVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -352,7 +356,7 @@ public class ObjectVisibilityTest
     @Test( expected = NoSuchObjectException.class )
     public void givenFromEntityWhenAccessingAboveLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -370,7 +374,7 @@ public class ObjectVisibilityTest
     @Test( expected = NoSuchObjectException.class )
     public void givenFromEntityWhenAccessingAboveModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -655,6 +659,8 @@ public class ObjectVisibilityTest
             module.objects( ModuleApplicationVisible.class ).visibleIn( Visibility.application );
             module.objects( ModuleLayerVisible.class ).visibleIn( Visibility.layer );
             module.objects( ModuleModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -672,6 +678,7 @@ public class ObjectVisibilityTest
             module.objects( BelowModuleVisible.class ).visibleIn( Visibility.module );
 
             new EntityTestAssembler().visibleIn( Visibility.application ).assemble( module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -687,6 +694,8 @@ public class ObjectVisibilityTest
             module.objects( AboveApplicationVisible.class ).visibleIn( Visibility.application );
             module.objects( AboveLayerVisible.class ).visibleIn( Visibility.layer );
             module.objects( AboveModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -701,6 +710,8 @@ public class ObjectVisibilityTest
             module.objects( BesideApplicationVisible.class ).visibleIn( Visibility.application );
             module.objects( BesideLayerVisible.class ).visibleIn( Visibility.layer );
             module.objects( BesideModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/property/ImmutablePropertyTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/property/ImmutablePropertyTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/property/ImmutablePropertyTest.java
index caed693..1ec9207 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/property/ImmutablePropertyTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/property/ImmutablePropertyTest.java
@@ -83,7 +83,7 @@ public final class ImmutablePropertyTest
     @Test
     public final void testImmutableEntityProperty()
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<LocationEntity> builder = uow.newEntityBuilder( LocationEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/query/IterableQuerySourceTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/query/IterableQuerySourceTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/query/IterableQuerySourceTest.java
index f8737cc..726c14a 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/query/IterableQuerySourceTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/query/IterableQuerySourceTest.java
@@ -20,6 +20,7 @@ package org.apache.zest.runtime.query;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -89,12 +90,13 @@ public class IterableQuerySourceTest
 
                 module.values( ContactsValue.class, ContactValue.class );
                 new EntityTestAssembler().assemble( module );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
-        uow = assembler.module().newUnitOfWork();
+        uow = assembler.module().unitOfWorkFactory().newUnitOfWork();
         Network.populate( uow, assembler.module() );
         uow.complete();
-        uow = assembler.module().newUnitOfWork();
+        uow = assembler.module().unitOfWorkFactory().newUnitOfWork();
         Network.refresh( uow );
         qbf = assembler.module();
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/query/NonQueryableTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/query/NonQueryableTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/query/NonQueryableTest.java
index b876242..2e3b67b 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/query/NonQueryableTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/query/NonQueryableTest.java
@@ -42,7 +42,7 @@ public class NonQueryableTest
     @Test
     public void whenQuerableIsFalseOnPropertyThenExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             QueryBuilder<Abc> builder = module.newQueryBuilder( Abc.class );
@@ -63,7 +63,7 @@ public class NonQueryableTest
     @Test
     public void testQueryIterable()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             module.newQueryBuilder( Abc2.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/service/AvailableServiceTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/service/AvailableServiceTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/service/AvailableServiceTest.java
index 47d4e0f..0e14d4a 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/service/AvailableServiceTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/service/AvailableServiceTest.java
@@ -14,6 +14,7 @@
 
 package org.apache.zest.runtime.service;
 
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
 import org.apache.zest.api.common.Optional;
@@ -50,6 +51,7 @@ public class AvailableServiceTest
                 throws AssemblyException
             {
                 module.services( TestServiceComposite1.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 
@@ -72,6 +74,7 @@ public class AvailableServiceTest
                 module.entities( TestServiceConfiguration.class );
 
                 new EntityTestAssembler().assemble( module );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 
@@ -100,6 +103,7 @@ public class AvailableServiceTest
                 module.entities( TestServiceConfiguration.class );
 
                 new EntityTestAssembler().assemble( module );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/service/ConfigurationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/service/ConfigurationTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/service/ConfigurationTest.java
index e5b947b..577dc80 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/service/ConfigurationTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/service/ConfigurationTest.java
@@ -58,7 +58,7 @@ public class ConfigurationTest
     {
         module.injectTo( this );
 
-        UnitOfWork unit = module.newUnitOfWork();
+        UnitOfWork unit = uowf.newUnitOfWork();
         EntityBuilder<HelloWorldConfiguration> entityBuilder = unit.newEntityBuilder( HelloWorldConfiguration.class, service
             .identity() );
         HelloWorldConfiguration config = entityBuilder.instance();
@@ -88,7 +88,7 @@ public class ConfigurationTest
         HelloWorldConfiguration config;
 
         {
-            UnitOfWork unit = module.newUnitOfWork();
+            UnitOfWork unit = uowf.newUnitOfWork();
             EntityBuilder<HelloWorldConfiguration> entityBuilder = unit.newEntityBuilder( HelloWorldConfiguration.class, service
                 .identity() );
             config = entityBuilder.instance();
@@ -101,7 +101,7 @@ public class ConfigurationTest
         assertThat( "result is correct", service.get().sayHello(), equalTo( "Hello World" ) );
 
         {
-            UnitOfWork unit = module.newUnitOfWork();
+            UnitOfWork unit = uowf.newUnitOfWork();
             config = unit.get( config );
             config.phrase().set( "Hey" );
             config.name().set( "Universe" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/service/ServiceVisibilityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/service/ServiceVisibilityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/service/ServiceVisibilityTest.java
index e1d9ae6..92edd73 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/service/ServiceVisibilityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/service/ServiceVisibilityTest.java
@@ -16,6 +16,8 @@
 
 package org.apache.zest.runtime.service;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -42,6 +44,7 @@ public class ServiceVisibilityTest
     private Energy4Java zest;
     private Module module;
     private Application app;
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void setup()
@@ -75,6 +78,7 @@ public class ServiceVisibilityTest
         } );
         app.activate();
         module = app.findModule( "From Layer", "From" );
+        uowf = module.unitOfWorkFactory();
     }
 
     @After
@@ -171,7 +175,7 @@ public class ServiceVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -189,7 +193,7 @@ public class ServiceVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -207,7 +211,7 @@ public class ServiceVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleModuleVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -225,7 +229,7 @@ public class ServiceVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -243,7 +247,7 @@ public class ServiceVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -261,7 +265,7 @@ public class ServiceVisibilityTest
     @Test( expected = NoSuchServiceException.class )
     public void givenFromEntityWhenAccessingBesideModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -279,7 +283,7 @@ public class ServiceVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBelowApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -297,7 +301,7 @@ public class ServiceVisibilityTest
     @Test( expected = NoSuchServiceException.class )
     public void givenFromEntityWhenAccessingBelowLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -315,7 +319,7 @@ public class ServiceVisibilityTest
     @Test( expected = NoSuchServiceException.class )
     public void givenFromEntityWhenAccessingBelowModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -333,7 +337,7 @@ public class ServiceVisibilityTest
     @Test( expected = NoSuchServiceException.class )
     public void givenFromEntityWhenAccessingAboveApplicationVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -351,7 +355,7 @@ public class ServiceVisibilityTest
     @Test( expected = NoSuchServiceException.class )
     public void givenFromEntityWhenAccessingAboveLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -369,7 +373,7 @@ public class ServiceVisibilityTest
     @Test( expected = NoSuchServiceException.class )
     public void givenFromEntityWhenAccessingAboveModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -654,6 +658,8 @@ public class ServiceVisibilityTest
             module.services( ModuleApplicationVisible.class ).visibleIn( Visibility.application );
             module.services( ModuleLayerVisible.class ).visibleIn( Visibility.layer );
             module.services( ModuleModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -671,6 +677,7 @@ public class ServiceVisibilityTest
             module.services( BelowModuleVisible.class ).visibleIn( Visibility.module );
 
             new EntityTestAssembler().visibleIn( Visibility.application ).assemble( module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -686,6 +693,7 @@ public class ServiceVisibilityTest
             module.services( AboveApplicationVisible.class ).visibleIn( Visibility.application );
             module.services( AboveLayerVisible.class ).visibleIn( Visibility.layer );
             module.services( AboveModuleVisible.class ).visibleIn( Visibility.module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -700,6 +708,7 @@ public class ServiceVisibilityTest
             module.services( BesideApplicationVisible.class ).visibleIn( Visibility.application );
             module.services( BesideLayerVisible.class ).visibleIn( Visibility.layer );
             module.services( BesideModuleVisible.class ).visibleIn( Visibility.module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/structure/TypeToCompositeLookupTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/structure/TypeToCompositeLookupTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/structure/TypeToCompositeLookupTest.java
index 520b528..d516ede 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/structure/TypeToCompositeLookupTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/structure/TypeToCompositeLookupTest.java
@@ -14,6 +14,8 @@
 package org.apache.zest.runtime.structure;
 
 import java.util.Iterator;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
 import org.apache.zest.api.composite.AmbiguousTypeException;
@@ -96,6 +98,7 @@ public class TypeToCompositeLookupTest
                 throws AssemblyException
             {
                 module.objects( SomeOtherFooImpl.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
         }.module();
@@ -117,6 +120,7 @@ public class TypeToCompositeLookupTest
                 throws AssemblyException
             {
                 module.objects( SomeOtherFooImpl.class, BasicFooImpl.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
         }.module();
@@ -146,6 +150,7 @@ public class TypeToCompositeLookupTest
                 throws AssemblyException
             {
                 module.transients( SomeOtherFoo.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
         }.module();
@@ -167,6 +172,7 @@ public class TypeToCompositeLookupTest
                 throws AssemblyException
             {
                 module.transients( SomeOtherFoo.class, BasicFoo.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
         }.module();
@@ -196,6 +202,7 @@ public class TypeToCompositeLookupTest
                 throws AssemblyException
             {
                 module.values( SomeOtherFoo.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
         }.module();
@@ -217,6 +224,7 @@ public class TypeToCompositeLookupTest
                 throws AssemblyException
             {
                 module.values( SomeOtherFoo.class, BasicFoo.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
         }.module();
@@ -238,7 +246,7 @@ public class TypeToCompositeLookupTest
     public void entities()
         throws UnitOfWorkCompletionException, ActivationException, AssemblyException
     {
-        Module module = new SingletonAssembler()
+        UnitOfWorkFactory uowf = new SingletonAssembler()
         {
 
             @Override
@@ -247,11 +255,12 @@ public class TypeToCompositeLookupTest
             {
                 new EntityTestAssembler().assemble( module );
                 module.entities( SomeOtherFoo.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
-        }.module();
+        }.module().unitOfWorkFactory();
 
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         SomeOtherFoo someOtherFoo = uow.newEntityBuilder( SomeOtherFoo.class ).newInstance();
         BasicFoo basicFoo = uow.newEntityBuilder( BasicFoo.class ).newInstance();
@@ -267,7 +276,7 @@ public class TypeToCompositeLookupTest
 
         uow.complete();
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
 
         uow.get( SomeOtherFoo.class, someOtherFooIdentity );
         uow.get( BasicFoo.class, basicFooIdentity );
@@ -280,7 +289,7 @@ public class TypeToCompositeLookupTest
     public void entitiesAmbiguousDeclaration()
         throws UnitOfWorkCompletionException, ActivationException, AssemblyException
     {
-        Module module = new SingletonAssembler()
+        UnitOfWorkFactory uowf = new SingletonAssembler()
         {
 
             @Override
@@ -289,11 +298,12 @@ public class TypeToCompositeLookupTest
             {
                 new EntityTestAssembler().assemble( module );
                 module.entities( SomeOtherFoo.class, BasicFoo.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
-        }.module();
+        }.module().unitOfWorkFactory();
 
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         SomeOtherFoo someOtherFoo = uow.newEntityBuilder( SomeOtherFoo.class ).newInstance();
         BasicFoo basicFoo = uow.newEntityBuilder( BasicFoo.class ).newInstance();
@@ -317,7 +327,7 @@ public class TypeToCompositeLookupTest
 
         uow.complete();
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
 
         assertEquals( CATHEDRAL, uow.get( SomeOtherFoo.class, someOtherFooIdentity ).bar() );
         assertEquals( BAZAR, uow.get( BasicFoo.class, basicFooIdentity ).bar() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/transients/TransientVisibilityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/transients/TransientVisibilityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/transients/TransientVisibilityTest.java
index 798830c..ad27219 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/transients/TransientVisibilityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/transients/TransientVisibilityTest.java
@@ -16,9 +16,6 @@
 
 package org.apache.zest.runtime.transients;
 
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
 import org.apache.zest.api.common.Visibility;
 import org.apache.zest.api.composite.NoSuchTransientException;
 import org.apache.zest.api.composite.TransientBuilder;
@@ -30,19 +27,25 @@ import org.apache.zest.api.service.ServiceComposite;
 import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueComposite;
 import org.apache.zest.bootstrap.ApplicationAssemblerAdapter;
 import org.apache.zest.bootstrap.Assembler;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.Energy4Java;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.test.EntityTestAssembler;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
 
 public class TransientVisibilityTest
 {
     private Energy4Java zest;
     private Module module;
     private Application app;
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void setup()
@@ -60,7 +63,7 @@ public class TransientVisibilityTest
                 { // Layer From
                   { // From Module
                     new FromAssembler(),
-                  },
+                    },
                   { // Beside Module
                     new BesideAssembler()
                   }
@@ -76,6 +79,7 @@ public class TransientVisibilityTest
         } );
         app.activate();
         module = app.findModule( "From Layer", "From" );
+        uowf = module.unitOfWorkFactory();
     }
 
     @After
@@ -172,7 +176,7 @@ public class TransientVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -190,7 +194,7 @@ public class TransientVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -208,7 +212,7 @@ public class TransientVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleModuleVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -226,7 +230,7 @@ public class TransientVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -244,7 +248,7 @@ public class TransientVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -262,7 +266,7 @@ public class TransientVisibilityTest
     @Test( expected = NoSuchTransientException.class )
     public void givenFromEntityWhenAccessingBesideModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -280,7 +284,7 @@ public class TransientVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBelowApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -298,7 +302,7 @@ public class TransientVisibilityTest
     @Test( expected = NoSuchTransientException.class )
     public void givenFromEntityWhenAccessingBelowLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -316,7 +320,7 @@ public class TransientVisibilityTest
     @Test( expected = NoSuchTransientException.class )
     public void givenFromEntityWhenAccessingBelowModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -334,7 +338,7 @@ public class TransientVisibilityTest
     @Test( expected = NoSuchTransientException.class )
     public void givenFromEntityWhenAccessingAboveApplicationVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -352,7 +356,7 @@ public class TransientVisibilityTest
     @Test( expected = NoSuchTransientException.class )
     public void givenFromEntityWhenAccessingAboveLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -370,7 +374,7 @@ public class TransientVisibilityTest
     @Test( expected = NoSuchTransientException.class )
     public void givenFromEntityWhenAccessingAboveModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -655,6 +659,8 @@ public class TransientVisibilityTest
             module.transients( ModuleApplicationVisible.class ).visibleIn( Visibility.application );
             module.transients( ModuleLayerVisible.class ).visibleIn( Visibility.layer );
             module.transients( ModuleModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -672,6 +678,8 @@ public class TransientVisibilityTest
             module.transients( BelowModuleVisible.class ).visibleIn( Visibility.module );
 
             new EntityTestAssembler().visibleIn( Visibility.application ).assemble( module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -687,6 +695,8 @@ public class TransientVisibilityTest
             module.transients( AboveApplicationVisible.class ).visibleIn( Visibility.application );
             module.transients( AboveLayerVisible.class ).visibleIn( Visibility.layer );
             module.transients( AboveModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -701,6 +711,8 @@ public class TransientVisibilityTest
             module.transients( BesideApplicationVisible.class ).visibleIn( Visibility.application );
             module.transients( BesideLayerVisible.class ).visibleIn( Visibility.layer );
             module.transients( BesideModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/AutoCloseableUoWTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/AutoCloseableUoWTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/AutoCloseableUoWTest.java
index 82439f3..a489767 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/AutoCloseableUoWTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/AutoCloseableUoWTest.java
@@ -54,7 +54,7 @@ public class AutoCloseableUoWTest
     public void givenGoodAutoCloseableUoWWhenTryWithResourceExpectSuccess()
         throws UnitOfWorkCompletionException
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             EntityBuilder<TestEntity> builder = uow.newEntityBuilder( TestEntity.class );
             builder.instance().mandatory().set( "Mandatory property" );
@@ -67,7 +67,7 @@ public class AutoCloseableUoWTest
     public void givenWrongAutoCloseableUoWWhenTryWithResourceExpectSuccess()
         throws UnitOfWorkCompletionException
     {
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             uow.newEntity( TestEntity.class );
             uow.complete();
@@ -77,7 +77,7 @@ public class AutoCloseableUoWTest
     @After
     public void afterEachTest()
     {
-        assertThat( module.isUnitOfWorkActive(), is( false ) );
+        assertThat( uowf.isUnitOfWorkActive(), is( false ) );
     }
 
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/PrivateEntityUnitOfWorkTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/PrivateEntityUnitOfWorkTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/PrivateEntityUnitOfWorkTest.java
index 86e2fba..1d81f68 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/PrivateEntityUnitOfWorkTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/PrivateEntityUnitOfWorkTest.java
@@ -14,7 +14,6 @@
 
 package org.apache.zest.runtime.unitofwork;
 
-import org.junit.Test;
 import org.apache.zest.api.association.Association;
 import org.apache.zest.api.association.ManyAssociation;
 import org.apache.zest.api.entity.EntityBuilder;
@@ -31,17 +30,14 @@ import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
 import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.api.value.ValueComposite;
-import org.apache.zest.bootstrap.ApplicationAssembler;
-import org.apache.zest.bootstrap.ApplicationAssembly;
-import org.apache.zest.bootstrap.ApplicationAssemblyFactory;
 import org.apache.zest.bootstrap.Assembler;
-import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.Energy4Java;
-import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.test.EntityTestAssembler;
+import org.junit.Test;
 
-import static org.junit.Assert.fail;
 import static org.apache.zest.api.common.Visibility.application;
+import static org.junit.Assert.fail;
 
 /**
  * JAVADOC
@@ -58,42 +54,29 @@ public class PrivateEntityUnitOfWorkTest
         System.setProperty( "zest.compacttrace", "off" );
 
         Energy4Java is = new Energy4Java();
-        Application app = is.newApplication( new ApplicationAssembler()
-        {
-            public ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
-                throws AssemblyException
-            {
-                return applicationFactory.newApplicationAssembly( new Assembler[][][]{
+        Application app = is.newApplication(
+            applicationFactory ->
+                applicationFactory.newApplicationAssembly( new Assembler[][][]{
                     {
                         {
-                            new Assembler()
-                            {
-                                public void assemble( ModuleAssembly module )
-                                    throws AssemblyException
-                                {
-                                    module.objects( PrivateEntityUnitOfWorkTest.class );
-                                }
+                            module -> {
+                                module.objects( PrivateEntityUnitOfWorkTest.class );
+                                new DefaultUnitOfWorkAssembler().assemble( module );
                             }
                         }
                     },
                     {
                         {
-                            new Assembler()
-                            {
-                                public void assemble( ModuleAssembly module )
-                                    throws AssemblyException
-                                {
-                                    module.entities( ProductEntity.class );
-                                    module.entities( ProductCatalogEntity.class ).visibleIn( application );
-                                    module.values( ProductInfo.class );
-                                    new EntityTestAssembler().assemble( module );
-                                }
+                            module -> {
+                                module.entities( ProductEntity.class );
+                                module.entities( ProductCatalogEntity.class ).visibleIn( application );
+                                module.values( ProductInfo.class );
+                                new EntityTestAssembler().assemble( module );
+                                new DefaultUnitOfWorkAssembler().assemble( module );
                             }
                         }
                     }
-                } );
-            }
-        } );
+                } ) );
         app.activate();
 
         Module module = app.findModule( "Layer 1", "Module 1" );
@@ -126,7 +109,7 @@ public class PrivateEntityUnitOfWorkTest
             unitOfWork.discard();
         }
 
-        unitOfWork = module.newUnitOfWork();
+        unitOfWork = uowf.newUnitOfWork();
         try
         {
             ProductCatalog catalog = unitOfWork.get( ProductCatalog.class, "1" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/RemovalTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/RemovalTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/RemovalTest.java
index d80267c..2cfaabc 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/RemovalTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/RemovalTest.java
@@ -46,14 +46,14 @@ public class RemovalTest
     public void givenUnitOfWorkHasBeenCreateWhenCreatingNewEntityThenFindNewEntityWithGet()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Abc> builder = uow.newEntityBuilder( Abc.class, "123" );
             builder.instance().name().set( "Niclas" );
             builder.newInstance();
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             Abc abc = uow.get( Abc.class, "123" );
             assertEquals( "Niclas", abc.name().get() );
         }
@@ -67,19 +67,19 @@ public class RemovalTest
     public void givenEntityCreatedWhenRemovingEntityThenFindNewEntityShouldNotExist()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Abc> builder = uow.newEntityBuilder( Abc.class, "123" );
             builder.instance().name().set( "Niclas" );
             builder.newInstance();
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             Abc abc = uow.get( Abc.class, "123" );
             assertEquals( "Niclas", abc.name().get() );
             uow.remove( abc );
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             uow.get( Abc.class, "123" );
             fail( "This '123' entity should not exist." );
         }
@@ -97,18 +97,18 @@ public class RemovalTest
     public void givenDetachedEntityWhenRemovingEntityThenFindNewEntityShouldNotExist()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Abc> builder = uow.newEntityBuilder( Abc.class, "123" );
             builder.instance().name().set( "Niclas" );
             Abc abc = builder.newInstance();
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             abc = uow.get( abc );  // Attach the detached entity to 'uow' session.
             uow.remove( abc );
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             uow.get( Abc.class, "123" );
             fail( "This '123' entity should not exist." );
         }
@@ -126,7 +126,7 @@ public class RemovalTest
     public void givenEntityCreatedWhenRemovingEntityBeforeCompletingUowThenFindNewEntityShouldNotExist()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<Abc> builder = uow.newEntityBuilder( Abc.class, "123" );
@@ -134,7 +134,7 @@ public class RemovalTest
             Abc abc = builder.newInstance();
             uow.remove( abc );
             uow.complete();
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             uow.get( Abc.class, "123" );
             fail( "This '123' entity should not exist." );
         }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryTest.java
index e084471..efd32bb 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/unitofwork/UnitOfWorkFactoryTest.java
@@ -50,7 +50,7 @@ public class UnitOfWorkFactoryTest
     public void testUnitOfWork()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
 
         // Create product
         EntityBuilder<ProductEntity> cb = unitOfWork.newEntityBuilder( ProductEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueComposite2Test.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueComposite2Test.java b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueComposite2Test.java
index 70c28d4..79f8151 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueComposite2Test.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueComposite2Test.java
@@ -18,6 +18,7 @@
 package org.apache.zest.runtime.value;
 
 import java.security.Guard;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Assert;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
@@ -47,6 +48,7 @@ public class ValueComposite2Test
             {
                 module.values( SomeValue.class );
                 module.services( DummyService.class );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
         ValueBuilder<Some> builder = app.module().newValueBuilder( Some.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueInjectionDeserializationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueInjectionDeserializationTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueInjectionDeserializationTest.java
index fb98815..ceb8c7a 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueInjectionDeserializationTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueInjectionDeserializationTest.java
@@ -60,14 +60,14 @@ public class ValueInjectionDeserializationTest
             builder.prototype().data().set( "Niclas" );
             Some value = builder.newInstance();
 
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             EntityBuilder<Niclas> eb = uow.newEntityBuilder( Niclas.class );
             eb.instance().value().set( value );
             Niclas niclas1 = eb.newInstance();
             String id = niclas1.identity().get();
             uow.complete();
 
-            uow = module.newUnitOfWork();
+            uow = uowf.newUnitOfWork();
             Niclas niclas2 = uow.get( Niclas.class, id );
             Some someValue = niclas2.value().get();
             Assert.assertEquals( someValue.data().get(), "Niclas" );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueVisibilityTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueVisibilityTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueVisibilityTest.java
index 4c4cdba..aa14297 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueVisibilityTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueVisibilityTest.java
@@ -16,6 +16,8 @@
 
 package org.apache.zest.runtime.value;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -44,6 +46,7 @@ public class ValueVisibilityTest
     private Energy4Java zest;
     private Module module;
     private Application app;
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void setup()
@@ -77,6 +80,7 @@ public class ValueVisibilityTest
         } );
         app.activate();
         module = app.findModule( "From Layer", "From" );
+        uowf = module.unitOfWorkFactory();
     }
 
     @After
@@ -173,7 +177,7 @@ public class ValueVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -191,7 +195,7 @@ public class ValueVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -209,7 +213,7 @@ public class ValueVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingModuleModuleVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -227,7 +231,7 @@ public class ValueVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -245,7 +249,7 @@ public class ValueVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBesideLayerVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -263,7 +267,7 @@ public class ValueVisibilityTest
     @Test( expected = NoSuchValueException.class )
     public void givenFromEntityWhenAccessingBesideModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -281,7 +285,7 @@ public class ValueVisibilityTest
     @Test
     public void givenFromEntityWhenAccessingBelowApplicationVisibleExpectSuccess()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -299,7 +303,7 @@ public class ValueVisibilityTest
     @Test( expected = NoSuchValueException.class )
     public void givenFromEntityWhenAccessingBelowLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -317,7 +321,7 @@ public class ValueVisibilityTest
     @Test( expected = NoSuchValueException.class )
     public void givenFromEntityWhenAccessingBelowModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -335,7 +339,7 @@ public class ValueVisibilityTest
     @Test( expected = NoSuchValueException.class )
     public void givenFromEntityWhenAccessingAboveApplicationVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -353,7 +357,7 @@ public class ValueVisibilityTest
     @Test( expected = NoSuchValueException.class )
     public void givenFromEntityWhenAccessingAboveLayerVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -371,7 +375,7 @@ public class ValueVisibilityTest
     @Test( expected = NoSuchValueException.class )
     public void givenFromEntityWhenAccessingAboveModuleVisibleExpectException()
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             FromEntity entity = unitOfWork.newEntity( FromEntity.class, "123" );
@@ -656,6 +660,8 @@ public class ValueVisibilityTest
             module.values( ModuleApplicationVisible.class ).visibleIn( Visibility.application );
             module.values( ModuleLayerVisible.class ).visibleIn( Visibility.layer );
             module.values( ModuleModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -673,6 +679,7 @@ public class ValueVisibilityTest
             module.values( BelowModuleVisible.class ).visibleIn( Visibility.module );
 
             new EntityTestAssembler().visibleIn( Visibility.application ).assemble( module );
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -688,6 +695,8 @@ public class ValueVisibilityTest
             module.values( AboveApplicationVisible.class ).visibleIn( Visibility.application );
             module.values( AboveLayerVisible.class ).visibleIn( Visibility.layer );
             module.values( AboveModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 
@@ -702,6 +711,8 @@ public class ValueVisibilityTest
             module.values( BesideApplicationVisible.class ).visibleIn( Visibility.application );
             module.values( BesideLayerVisible.class ).visibleIn( Visibility.layer );
             module.values( BesideModuleVisible.class ).visibleIn( Visibility.module );
+
+            new DefaultUnitOfWorkAssembler().assemble( module );
         }
     }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueWithAssociationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueWithAssociationTest.java b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueWithAssociationTest.java
index 4afb9ce..c16af32 100644
--- a/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueWithAssociationTest.java
+++ b/core/runtime/src/test/java/org/apache/zest/runtime/value/ValueWithAssociationTest.java
@@ -65,7 +65,7 @@ public class ValueWithAssociationTest extends AbstractZestTest
         String identity1;
         String identity2;
         DualFaced value;
-        try (UnitOfWork uow = module.newUnitOfWork())
+        try (UnitOfWork uow = uowf.newUnitOfWork())
         {
             EntityBuilder<SimpleName> builder1 = uow.newEntityBuilder( SimpleName.class );
             builder1.instance().name().set( "Niclas" );
@@ -85,7 +85,7 @@ public class ValueWithAssociationTest extends AbstractZestTest
             uow.complete();
         }
 
-        try (UnitOfWork uow = module.newUnitOfWork())
+        try (UnitOfWork uow = uowf.newUnitOfWork())
         {
             DualFaced entity = uow.get( DualFaced.class, identity2 );
             AssociationStateHolder holder = spi.stateOf( (EntityComposite) entity );
@@ -118,13 +118,13 @@ public class ValueWithAssociationTest extends AbstractZestTest
         builder.prototype().name().set( "Hedhman" );
         DualFaced value = builder.newInstance();
 
-        try (UnitOfWork uow = module.newUnitOfWork())
+        try (UnitOfWork uow = uowf.newUnitOfWork())
         {
             uow.toEntity( DualFaced.class, value );
             uow.complete();
         }
 
-        try (UnitOfWork uow = module.newUnitOfWork())
+        try (UnitOfWork uow = uowf.newUnitOfWork())
         {
             DualFaced entity = uow.get( DualFaced.class, "1234" );
             assertThat( entity.identity().get(), equalTo( "1234" ) );
@@ -139,7 +139,7 @@ public class ValueWithAssociationTest extends AbstractZestTest
     {
         String identity1;
         String identity2;
-        try (UnitOfWork uow = module.newUnitOfWork())
+        try (UnitOfWork uow = uowf.newUnitOfWork())
         {
             EntityBuilder<SimpleName> builder1 = uow.newEntityBuilder( SimpleName.class );
             builder1.instance().name().set( "Niclas" );
@@ -169,7 +169,7 @@ public class ValueWithAssociationTest extends AbstractZestTest
         vb2.prototype().namedSimples().put( "paul", simpleValue );
         DualFaced dualValue = vb2.newInstance();
 
-        try (UnitOfWork uow = module.newUnitOfWork())
+        try (UnitOfWork uow = uowf.newUnitOfWork())
         {
             DualFaced dualEntity = uow.toEntity( DualFaced.class, dualValue );
             // The root entity is expected to have changed value,


[8/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleInstance.java
index bb9aa65..4bf431f 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleInstance.java
@@ -23,9 +23,7 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Stack;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.BiFunction;
 import java.util.function.Function;
 import java.util.function.Predicate;
 import java.util.stream.Stream;
@@ -42,7 +40,6 @@ import org.apache.zest.api.composite.ModelDescriptor;
 import org.apache.zest.api.composite.NoSuchTransientException;
 import org.apache.zest.api.composite.TransientBuilder;
 import org.apache.zest.api.composite.TransientDescriptor;
-import org.apache.zest.api.entity.EntityComposite;
 import org.apache.zest.api.entity.EntityDescriptor;
 import org.apache.zest.api.entity.EntityReference;
 import org.apache.zest.api.entity.IdentityGenerator;
@@ -58,10 +55,8 @@ import org.apache.zest.api.service.NoSuchServiceException;
 import org.apache.zest.api.service.ServiceDescriptor;
 import org.apache.zest.api.service.ServiceReference;
 import org.apache.zest.api.structure.Module;
-import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkException;
 import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
-import org.apache.zest.api.usecase.Usecase;
 import org.apache.zest.api.util.NullArgumentException;
 import org.apache.zest.api.value.NoSuchValueException;
 import org.apache.zest.api.value.ValueBuilder;
@@ -73,13 +68,10 @@ import org.apache.zest.runtime.activation.ActivationDelegate;
 import org.apache.zest.runtime.composite.FunctionStateResolver;
 import org.apache.zest.runtime.composite.StateResolver;
 import org.apache.zest.runtime.composite.TransientBuilderInstance;
-import org.apache.zest.runtime.composite.TransientModel;
 import org.apache.zest.runtime.composite.TransientStateInstance;
 import org.apache.zest.runtime.composite.TransientsModel;
 import org.apache.zest.runtime.composite.UsesInstance;
 import org.apache.zest.runtime.entity.EntitiesModel;
-import org.apache.zest.runtime.entity.EntityInstance;
-import org.apache.zest.runtime.entity.EntityModel;
 import org.apache.zest.runtime.injection.InjectionContext;
 import org.apache.zest.runtime.object.ObjectModel;
 import org.apache.zest.runtime.object.ObjectsModel;
@@ -90,21 +82,18 @@ import org.apache.zest.runtime.service.ImportedServicesInstance;
 import org.apache.zest.runtime.service.ImportedServicesModel;
 import org.apache.zest.runtime.service.ServicesInstance;
 import org.apache.zest.runtime.service.ServicesModel;
-import org.apache.zest.runtime.unitofwork.UnitOfWorkInstance;
 import org.apache.zest.runtime.value.ValueBuilderInstance;
 import org.apache.zest.runtime.value.ValueBuilderWithPrototype;
 import org.apache.zest.runtime.value.ValueBuilderWithState;
 import org.apache.zest.runtime.value.ValueInstance;
-import org.apache.zest.runtime.value.ValueModel;
 import org.apache.zest.runtime.value.ValuesModel;
 import org.apache.zest.spi.entitystore.EntityStore;
 import org.apache.zest.spi.metrics.MetricsProviderAdapter;
-import org.apache.zest.spi.module.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.valueserialization.orgjson.OrgJsonValueSerialization;
 
 import static java.util.stream.Stream.concat;
-import static org.apache.zest.api.util.Classes.RAW_CLASS;
 import static org.apache.zest.api.util.Classes.modelTypeSpecification;
 import static org.apache.zest.functional.Iterables.iterable;
 import static org.apache.zest.runtime.legacy.Specifications.translate;
@@ -126,15 +115,15 @@ public class ModuleInstance
     private final ImportedServicesInstance importedServices;
     // Eager instance objects
     private final ActivationDelegate activation;
-    private final TypeLookup typeLookup;
+    private final TypeLookupImpl typeLookup;
     private final QueryBuilderFactory queryBuilderFactory;
     private final ClassLoader classLoader;
-    private final EntityFunction entityFunction;
     // Lazy assigned on accessors
     private EntityStore store;
     private IdentityGenerator generator;
     private ValueSerialization valueSerialization;
     private MetricsProvider metrics;
+    private UnitOfWorkFactory uowf;
 
     @SuppressWarnings( "LeakingThisInConstructor" )
     public ModuleInstance( ModuleModel moduleModel, LayerInstance layerInstance, TransientsModel transientsModel,
@@ -147,17 +136,16 @@ public class ModuleInstance
         layer = layerInstance;
         transients = transientsModel;
         values = valuesModel;
-        objects = objectsModel;
         entities = entitiesModel;
         services = servicesModel.newInstance( this );
+        objects = objectsModel;
         importedServices = importedServicesModel.newInstance( this );
 
         // Eager instance objects
         activation = new ActivationDelegate( this );
-        typeLookup = new TypeLookup( this );
+        typeLookup = new TypeLookupImpl( this );
         queryBuilderFactory = new QueryBuilderFactoryImpl( this );
         classLoader = new ModuleClassLoader( this, Thread.currentThread().getContextClassLoader() );
-        entityFunction = new EntityFunction( this );
 
         // Activation
         services.registerActivationEventListener( activation );
@@ -316,7 +304,7 @@ public class ModuleInstance
         }
 
         InjectionContext injectionContext = new InjectionContext( modelModule.module(), UsesInstance.EMPTY_USES.use( uses ) );
-        return mixinType.cast( ((ObjectModel) modelModule.model()).newInstance( injectionContext ) );
+        return mixinType.cast( ( (ObjectModel) modelModule.model() ).newInstance( injectionContext ) );
     }
 
     @Override
@@ -332,7 +320,7 @@ public class ModuleInstance
         }
 
         InjectionContext injectionContext = new InjectionContext( modelModule.module(), UsesInstance.EMPTY_USES.use( uses ) );
-        ((ObjectModel) modelModule.model()).inject( injectionContext, instance );
+        ( (ObjectModel) modelModule.model() ).inject( injectionContext, instance );
     }
 
     // Implementation of TransientBuilderFactory
@@ -352,7 +340,7 @@ public class ModuleInstance
         modelModule.model().state().properties().forEach(
             propertyModel ->
             {
-                Property<?> property = new PropertyInstance<>( ((PropertyModel) propertyModel).getBuilderInfo(),
+                Property<?> property = new PropertyInstance<>( ( (PropertyModel) propertyModel ).getBuilderInfo(),
                                                                propertyModel.initialValue( modelModule.module() ) );
                 properties.put( propertyModel.accessor(), property );
             } );
@@ -495,57 +483,6 @@ public class ModuleInstance
         }
     }
 
-    // Implementation of UnitOfWorkFactory
-    @Override
-    public UnitOfWork newUnitOfWork()
-    {
-        return newUnitOfWork( Usecase.DEFAULT );
-    }
-
-    @Override
-    public UnitOfWork newUnitOfWork( long currentTime )
-    {
-        return newUnitOfWork( Usecase.DEFAULT, currentTime );
-    }
-
-    @Override
-    public UnitOfWork newUnitOfWork( Usecase usecase )
-    {
-        return newUnitOfWork( usecase == null ? Usecase.DEFAULT : usecase, System.currentTimeMillis() );
-    }
-
-    @Override
-    public UnitOfWork newUnitOfWork( Usecase usecase, long currentTime )
-    {
-        UnitOfWorkInstance unitOfWorkInstance = new UnitOfWorkInstance( usecase, currentTime, metricsProvider() );
-        return new ModuleUnitOfWork( ModuleInstance.this, unitOfWorkInstance );
-    }
-
-    @Override
-    public boolean isUnitOfWorkActive()
-    {
-        Stack<UnitOfWorkInstance> stack = UnitOfWorkInstance.getCurrent();
-        return !stack.isEmpty();
-    }
-
-    @Override
-    public UnitOfWork currentUnitOfWork()
-    {
-        Stack<UnitOfWorkInstance> stack = UnitOfWorkInstance.getCurrent();
-        if( stack.size() == 0 )
-        {
-            throw new IllegalStateException( "No current UnitOfWork active" );
-        }
-        return new ModuleUnitOfWork( ModuleInstance.this, stack.peek() );
-    }
-
-    @Override
-    public UnitOfWork getUnitOfWork( EntityComposite entity )
-    {
-        EntityInstance instance = EntityInstance.entityInstanceOf( entity );
-        return instance.unitOfWork();
-    }
-
     // Implementation of QueryBuilderFactory
     @Override
     public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
@@ -617,42 +554,24 @@ public class ModuleInstance
         return layer;
     }
 
-    public TypeLookup typeLookup()
+    @Override
+    public TypeLookupImpl typeLookup()
     {
         return typeLookup;
     }
 
-    public BiFunction<EntityReference, Type, Object> getEntityFunction()
-    {
-        return entityFunction;
-    }
-
-    private static class EntityFunction
-        implements BiFunction<EntityReference, Type, Object>
-    {
-
-        private final UnitOfWorkFactory uowf;
-
-        private EntityFunction( UnitOfWorkFactory uowf )
-        {
-            this.uowf = uowf;
-        }
-
-        @Override
-        public Object apply( EntityReference entityReference, Type type )
-        {
-            return uowf.currentUnitOfWork().get( RAW_CLASS.apply( type ), entityReference.identity() );
-        }
-    }
-
     public EntityStore entityStore()
     {
         synchronized( this )
         {
             if( store == null )
             {
-                ServiceReference<EntityStore> service = findService( EntityStore.class );
-                if( service == null )
+                ServiceReference<EntityStore> service = null;
+                try
+                {
+                    service = findService( EntityStore.class );
+                }
+                catch( NoSuchServiceException e )
                 {
                     throw new UnitOfWorkException( "No EntityStore service available in module " + name() );
                 }
@@ -662,6 +581,27 @@ public class ModuleInstance
         return store;
     }
 
+    public UnitOfWorkFactory unitOfWorkFactory()
+    {
+        synchronized( this )
+        {
+            if( uowf == null )
+            {
+                ServiceReference<UnitOfWorkFactory> service = null;
+                try
+                {
+                    service = findService( UnitOfWorkFactory.class );
+                }
+                catch( NoSuchServiceException e )
+                {
+                    throw new UnitOfWorkException( "No UnitOfWorkFactory service available in module " + name() );
+                }
+                uowf = service.get();
+            }
+        }
+        return uowf;
+    }
+
     public IdentityGenerator identityGenerator()
     {
         synchronized( this )
@@ -695,7 +635,7 @@ public class ModuleInstance
         return valueSerialization;
     }
 
-    /* package */ MetricsProvider metricsProvider()
+    public MetricsProvider metricsProvider()
     {
         synchronized( this )
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleUnitOfWork.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleUnitOfWork.java b/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleUnitOfWork.java
deleted file mode 100755
index b5303d5..0000000
--- a/core/runtime/src/main/java/org/apache/zest/runtime/structure/ModuleUnitOfWork.java
+++ /dev/null
@@ -1,769 +0,0 @@
-/*
- * Copyright (c) 2009, Rickard Öberg. All Rights Reserved.
- * Copyright (c) 2013-2015, Niclas Hedhman. All Rights Reserved.
- * Copyright (c) 2013-2015, Paul Merlin. All Rights Reserved.
- *
- * Licensed 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.zest.runtime.structure;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.function.Predicate;
-import org.apache.zest.api.association.AssociationDescriptor;
-import org.apache.zest.api.association.AssociationStateHolder;
-import org.apache.zest.api.common.QualifiedName;
-import org.apache.zest.api.composite.Composite;
-import org.apache.zest.api.entity.EntityBuilder;
-import org.apache.zest.api.entity.EntityComposite;
-import org.apache.zest.api.entity.EntityDescriptor;
-import org.apache.zest.api.entity.EntityReference;
-import org.apache.zest.api.entity.Identity;
-import org.apache.zest.api.entity.IdentityGenerator;
-import org.apache.zest.api.entity.LifecycleException;
-import org.apache.zest.api.property.Property;
-import org.apache.zest.api.property.PropertyDescriptor;
-import org.apache.zest.api.property.StateHolder;
-import org.apache.zest.api.query.Query;
-import org.apache.zest.api.query.QueryBuilder;
-import org.apache.zest.api.query.QueryExecutionException;
-import org.apache.zest.api.query.grammar.OrderBy;
-import org.apache.zest.api.service.NoSuchServiceException;
-import org.apache.zest.api.unitofwork.ConcurrentEntityModificationException;
-import org.apache.zest.api.unitofwork.EntityTypeNotFoundException;
-import org.apache.zest.api.unitofwork.NoSuchEntityException;
-import org.apache.zest.api.unitofwork.UnitOfWork;
-import org.apache.zest.api.unitofwork.UnitOfWorkCallback;
-import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
-import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
-import org.apache.zest.api.usecase.Usecase;
-import org.apache.zest.api.util.NullArgumentException;
-import org.apache.zest.api.value.ValueBuilder;
-import org.apache.zest.api.value.ValueComposite;
-import org.apache.zest.functional.Iterables;
-import org.apache.zest.runtime.association.AssociationInstance;
-import org.apache.zest.runtime.association.ManyAssociationInstance;
-import org.apache.zest.runtime.association.NamedAssociationInstance;
-import org.apache.zest.runtime.composite.FunctionStateResolver;
-import org.apache.zest.runtime.entity.EntityInstance;
-import org.apache.zest.runtime.entity.EntityModel;
-import org.apache.zest.runtime.property.PropertyModel;
-import org.apache.zest.runtime.unitofwork.EntityBuilderInstance;
-import org.apache.zest.runtime.unitofwork.UnitOfWorkInstance;
-import org.apache.zest.runtime.value.ValueInstance;
-import org.apache.zest.spi.entity.EntityState;
-import org.apache.zest.spi.entity.EntityStatus;
-import org.apache.zest.spi.entity.NamedAssociationState;
-import org.apache.zest.spi.entitystore.EntityStore;
-import org.apache.zest.spi.module.ModelModule;
-import org.apache.zest.spi.query.EntityFinder;
-import org.apache.zest.spi.query.EntityFinderException;
-import org.apache.zest.spi.query.QueryBuilderSPI;
-import org.apache.zest.spi.query.QuerySource;
-
-import static org.apache.zest.api.entity.EntityReference.parseEntityReference;
-
-/**
- * JAVADOC
- */
-public class ModuleUnitOfWork
-    implements UnitOfWork
-{
-    private static final QualifiedName IDENTITY_STATE_NAME;
-
-    static
-    {
-        try
-        {
-            IDENTITY_STATE_NAME = QualifiedName.fromAccessor( Identity.class.getMethod( "identity" ) );
-        }
-        catch( NoSuchMethodException e )
-        {
-            throw new InternalError( "Zest Core Runtime codebase is corrupted. Contact Zest team: ModuleUnitOfWork" );
-        }
-    }
-
-    private final UnitOfWorkInstance uow;
-    private final ModuleInstance module;
-
-    ModuleUnitOfWork( ModuleInstance module, UnitOfWorkInstance uow )
-    {
-        this.module = module;
-        this.uow = uow;
-    }
-
-    public ModuleInstance module()
-    {
-        return module;
-    }
-
-    public UnitOfWorkInstance instance()
-    {
-        return uow;
-    }
-
-    @Override
-    public UnitOfWorkFactory unitOfWorkFactory()
-    {
-        return module;
-    }
-
-    @Override
-    public long currentTime()
-    {
-        return uow.currentTime();
-    }
-
-    @Override
-    public Usecase usecase()
-    {
-        return uow.usecase();
-    }
-
-    @Override
-    public <T> T metaInfo( Class<T> infoType )
-    {
-        return uow.metaInfo().get( infoType );
-    }
-
-    @Override
-    public void setMetaInfo( Object metaInfo )
-    {
-        uow.metaInfo().set( metaInfo );
-    }
-
-    @Override
-    @SuppressWarnings( { "raw", "unchecked" } )
-    public <T> Query<T> newQuery( QueryBuilder<T> queryBuilder )
-    {
-        QueryBuilderSPI queryBuilderSPI = (QueryBuilderSPI) queryBuilder;
-
-        return queryBuilderSPI.newQuery( new UoWQuerySource( this ) );
-    }
-
-    @Override
-    public <T> T newEntity( Class<T> type )
-        throws EntityTypeNotFoundException, LifecycleException
-    {
-        return newEntity( type, null );
-    }
-
-    @Override
-    public <T> T newEntity( Class<T> type, String identity )
-        throws EntityTypeNotFoundException, LifecycleException
-    {
-        return newEntityBuilder( type, identity ).newInstance();
-    }
-
-    @Override
-    public <T> EntityBuilder<T> newEntityBuilder( Class<T> type )
-        throws EntityTypeNotFoundException
-    {
-        return newEntityBuilder( type, null );
-    }
-
-    @Override
-    public <T> EntityBuilder<T> newEntityBuilder( Class<T> type, String identity )
-        throws EntityTypeNotFoundException
-    {
-        ModelModule<EntityDescriptor> model = module.typeLookup().lookupEntityModel( type );
-
-        if( model == null )
-        {
-            throw new EntityTypeNotFoundException( type.getName(),
-                                                   module.name(),
-                                                   module.findVisibleEntityTypes().map( ModelModule.toStringFunction )
-            );
-        }
-
-        EntityStore entityStore = model.module().entityStore();
-
-        // Generate id if necessary
-        if( identity == null )
-        {
-            IdentityGenerator idGen = model.module().identityGenerator();
-            if( idGen == null )
-            {
-                throw new NoSuchServiceException( IdentityGenerator.class.getName(), model.module().name() );
-            }
-            identity = idGen.generate( model.model().types().findFirst().orElse( null ) );
-        }
-        EntityBuilder<T> builder;
-
-        builder = new EntityBuilderInstance<>( model,
-                                               this,
-                                               uow.getEntityStoreUnitOfWork( entityStore ),
-                                               identity );
-        return builder;
-    }
-
-    @Override
-    public <T> EntityBuilder<T> newEntityBuilderWithState(
-        Class<T> type,
-        Function<PropertyDescriptor, Object> propertyFunction,
-        Function<AssociationDescriptor, EntityReference> associationFunction,
-        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssociationFunction,
-        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssociationFunction
-    )
-        throws EntityTypeNotFoundException
-    {
-        return newEntityBuilderWithState( type, null,
-                                          propertyFunction,
-                                          associationFunction,
-                                          manyAssociationFunction,
-                                          namedAssociationFunction );
-    }
-
-    @Override
-    public <T> EntityBuilder<T> newEntityBuilderWithState(
-        Class<T> type, String identity,
-        Function<PropertyDescriptor, Object> propertyFunction,
-        Function<AssociationDescriptor, EntityReference> associationFunction,
-        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssociationFunction,
-        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssociationFunction
-    )
-        throws EntityTypeNotFoundException
-    {
-        NullArgumentException.validateNotNull( "propertyFunction", propertyFunction );
-        NullArgumentException.validateNotNull( "associationFunction", associationFunction );
-        NullArgumentException.validateNotNull( "manyAssociationFunction", manyAssociationFunction );
-        NullArgumentException.validateNotNull( "namedAssociationFunction", namedAssociationFunction );
-
-        ModelModule<EntityDescriptor> model = module.typeLookup().lookupEntityModel( type );
-
-        if( model == null )
-        {
-            throw new EntityTypeNotFoundException( type.getName(),
-                                                   module.name(),
-                                                   module.findVisibleEntityTypes().map( ModelModule.toStringFunction )
-            );
-        }
-
-        EntityStore entityStore = model.module().entityStore();
-
-        FunctionStateResolver stateResolver = new FunctionStateResolver(
-            propertyFunction, associationFunction, manyAssociationFunction, namedAssociationFunction
-        );
-
-        if( identity == null )
-        {
-            // Use identity from StateResolver if available
-            PropertyModel identityModel = (PropertyModel) model.model().state().findPropertyModelByQualifiedName( IDENTITY_STATE_NAME );
-            identity = (String) stateResolver.getPropertyState( identityModel );
-            if( identity == null )
-            {
-                // Generate identity
-                IdentityGenerator idGen = model.module().identityGenerator();
-                if( idGen == null )
-                {
-                    throw new NoSuchServiceException( IdentityGenerator.class.getName(), model.module().name() );
-                }
-                identity = idGen.generate( model.model().types().findFirst().orElse( null ));
-            }
-        }
-
-        return new EntityBuilderInstance<>( model,
-                                            this,
-                                            uow.getEntityStoreUnitOfWork( entityStore ),
-                                            identity,
-                                            stateResolver );
-    }
-
-    @Override
-    public <T> T get( Class<T> type, String identity )
-        throws EntityTypeNotFoundException, NoSuchEntityException
-    {
-        Iterable<ModelModule<EntityDescriptor>> models = module.typeLookup().lookupEntityModels( type );
-
-        if( !models.iterator().hasNext() )
-        {
-            throw new EntityTypeNotFoundException( type.getName(),
-                                                   module.name(),
-                                                   module.findVisibleEntityTypes().map( ModelModule.toStringFunction )
-            );
-        }
-
-        return uow.get( parseEntityReference( identity ), this, models, type );
-    }
-
-    @Override
-    @SuppressWarnings( "unchecked" )
-    public <T> T get( T entity )
-        throws EntityTypeNotFoundException
-    {
-        EntityComposite entityComposite = (EntityComposite) entity;
-        EntityInstance compositeInstance = EntityInstance.entityInstanceOf( entityComposite );
-        ModelModule<EntityDescriptor> model = new ModelModule<>( compositeInstance.module(), compositeInstance.entityModel() );
-        Class<T> type = (Class<T>) compositeInstance.types().findFirst().orElse( null );
-        return uow.get( compositeInstance.identity(), this, Collections.singletonList( model ), type );
-    }
-
-    @Override
-    public void remove( Object entity )
-        throws LifecycleException
-    {
-        uow.checkOpen();
-
-        EntityComposite entityComposite = (EntityComposite) entity;
-
-        EntityInstance compositeInstance = EntityInstance.entityInstanceOf( entityComposite );
-
-        if( compositeInstance.status() == EntityStatus.NEW )
-        {
-            compositeInstance.remove( this );
-            uow.remove( compositeInstance.identity() );
-        }
-        else if( compositeInstance.status() == EntityStatus.LOADED || compositeInstance.status() == EntityStatus.UPDATED )
-        {
-            compositeInstance.remove( this );
-        }
-        else
-        {
-            throw new NoSuchEntityException( compositeInstance.identity(), compositeInstance.types(), usecase() );
-        }
-    }
-
-    @SuppressWarnings( "DuplicateThrows" )
-    @Override
-    public void complete()
-        throws UnitOfWorkCompletionException, ConcurrentEntityModificationException
-    {
-        uow.complete();
-    }
-
-    @Override
-    public void discard()
-    {
-        uow.discard();
-    }
-
-    @Override
-    public void close()
-    {
-        discard();
-    }
-
-    @Override
-    public boolean isOpen()
-    {
-        return uow.isOpen();
-    }
-
-    @Override
-    public boolean isPaused()
-    {
-        return uow.isPaused();
-    }
-
-    @Override
-    public void pause()
-    {
-        uow.pause();
-    }
-
-    @Override
-    public void resume()
-    {
-        uow.resume();
-    }
-
-    @Override
-    public void addUnitOfWorkCallback( UnitOfWorkCallback callback )
-    {
-        uow.addUnitOfWorkCallback( callback );
-    }
-
-    @Override
-    public void removeUnitOfWorkCallback( UnitOfWorkCallback callback )
-    {
-        uow.removeUnitOfWorkCallback( callback );
-    }
-
-    @Override
-    public boolean equals( Object o )
-    {
-        if( this == o )
-        {
-            return true;
-        }
-        if( o == null || getClass() != o.getClass() )
-        {
-            return false;
-        }
-
-        ModuleUnitOfWork that = (ModuleUnitOfWork) o;
-
-        return uow.equals( that.uow );
-    }
-
-    @Override
-    public int hashCode()
-    {
-        return uow.hashCode();
-    }
-
-    @Override
-    public String toString()
-    {
-        return uow.toString();
-    }
-
-    public void addEntity( EntityInstance instance )
-    {
-        uow.addEntity( instance );
-    }
-
-    @Override
-    public <T extends Identity> T toValue( Class<T> primaryType, T entityComposite )
-    {
-        Function<PropertyDescriptor, Object> propertyFunction = new ToValuePropertyMappingFunction( entityComposite );
-        Function<AssociationDescriptor, EntityReference> assocationFunction = new ToValueAssociationMappingFunction<>( entityComposite );
-        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssocFunction = new ToValueManyAssociationMappingFunction<>( entityComposite );
-        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssocFunction = new ToValueNameAssociationMappingFunction<>( entityComposite );
-
-        @SuppressWarnings( "unchecked" )
-        ValueBuilder<T> builder = module().newValueBuilderWithState(
-            primaryType, propertyFunction, assocationFunction, manyAssocFunction, namedAssocFunction );
-        return builder.newInstance();
-    }
-
-    @Override
-    public <T extends Identity> T toEntity( Class<T> primaryType, T valueComposite )
-    {
-        Function<PropertyDescriptor, Object> propertyFunction = new ToEntityPropertyMappingFunction<>( valueComposite );
-        Function<AssociationDescriptor, EntityReference> assocationFunction = new ToEntityAssociationMappingFunction<>( valueComposite );
-        Function<AssociationDescriptor, Iterable<EntityReference>> manyAssocFunction = new ToEntityManyAssociationMappingFunction<>( valueComposite );
-        Function<AssociationDescriptor, Map<String, EntityReference>> namedAssocFunction = new ToEntityNameAssociationMappingFunction<>( valueComposite );
-
-        String identity = valueComposite.identity().get();
-        try
-        {
-            T entity = get( primaryType, identity );
-            // If successful, then this entity is to by modified.
-            EntityInstance instance = EntityInstance.entityInstanceOf( (EntityComposite) entity );
-            EntityState state = instance.entityState();
-            FunctionStateResolver stateResolver = new FunctionStateResolver( propertyFunction,
-                                                                             assocationFunction,
-                                                                             manyAssocFunction,
-                                                                             namedAssocFunction );
-            EntityModel model = (EntityModel) EntityInstance.entityInstanceOf( (EntityComposite) entity ).descriptor();
-            stateResolver.populateState( model, state );
-            return entity;
-        }
-        catch( NoSuchEntityException e )
-        {
-            EntityBuilder<T> entityBuilder = newEntityBuilderWithState( primaryType,
-                                                                        identity,
-                                                                        propertyFunction,
-                                                                        assocationFunction,
-                                                                        manyAssocFunction,
-                                                                        namedAssocFunction );
-            return entityBuilder.newInstance();
-        }
-    }
-
-    private static class UoWQuerySource implements QuerySource
-    {
-        private final ModuleUnitOfWork moduleUnitOfWork;
-
-        private UoWQuerySource( ModuleUnitOfWork moduleUnitOfWork )
-        {
-            this.moduleUnitOfWork = moduleUnitOfWork;
-        }
-
-        @Override
-        public <T> T find( Class<T> resultType,
-                           Predicate<Composite> whereClause,
-                           Iterable<OrderBy> orderBySegments,
-                           Integer firstResult,
-                           Integer maxResults,
-                           Map<String, Object> variables
-        )
-        {
-            final EntityFinder entityFinder = moduleUnitOfWork.module().findService( EntityFinder.class ).get();
-
-            try
-            {
-                final EntityReference foundEntity = entityFinder.findEntity( resultType, whereClause, variables == null ? Collections
-                    .<String, Object>emptyMap() : variables );
-                if( foundEntity != null )
-                {
-                    try
-                    {
-                        return moduleUnitOfWork.get( resultType, foundEntity.identity() );
-                    }
-                    catch( NoSuchEntityException e )
-                    {
-                        return null; // Index is out of sync - entity has been removed
-                    }
-                }
-                // No entity was found
-                return null;
-            }
-            catch( EntityFinderException e )
-            {
-                throw new QueryExecutionException( "Finder caused exception", e );
-            }
-        }
-
-        @Override
-        public <T> long count( Class<T> resultType,
-                               Predicate<Composite> whereClause,
-                               Iterable<OrderBy> orderBySegments,
-                               Integer firstResult,
-                               Integer maxResults,
-                               Map<String, Object> variables
-        )
-        {
-            final EntityFinder entityFinder = moduleUnitOfWork.module().findService( EntityFinder.class ).get();
-
-            try
-            {
-                return entityFinder.countEntities( resultType, whereClause, variables == null ? Collections.<String, Object>emptyMap() : variables );
-            }
-            catch( EntityFinderException e )
-            {
-                e.printStackTrace();
-                return 0;
-            }
-        }
-
-        @Override
-        public <T> Iterator<T> iterator( final Class<T> resultType,
-                                         Predicate<Composite> whereClause,
-                                         Iterable<OrderBy> orderBySegments,
-                                         Integer firstResult,
-                                         Integer maxResults,
-                                         Map<String, Object> variables
-        )
-        {
-            final EntityFinder entityFinder = moduleUnitOfWork.module().findService( EntityFinder.class ).get();
-
-            try
-            {
-                final Iterator<EntityReference> foundEntities = entityFinder.findEntities( resultType,
-                                                                                           whereClause,
-                                                                                           Iterables.toArray( OrderBy.class, orderBySegments ),
-                                                                                           firstResult,
-                                                                                           maxResults,
-                                                                                           variables == null ? Collections
-                                                                                               .<String, Object>emptyMap() : variables )
-                    .iterator();
-
-                return new Iterator<T>()
-                {
-                    @Override
-                    public boolean hasNext()
-                    {
-                        return foundEntities.hasNext();
-                    }
-
-                    @Override
-                    public T next()
-                    {
-                        final EntityReference foundEntity = foundEntities.next();
-                        try
-                        {
-                            return moduleUnitOfWork.get( resultType, foundEntity.identity() );
-                        }
-                        catch( NoSuchEntityException e )
-                        {
-                            // Index is out of sync - entity has been removed
-                            return null;
-                        }
-                    }
-
-                    @Override
-                    public void remove()
-                    {
-                        throw new UnsupportedOperationException();
-                    }
-                };
-            }
-            catch( EntityFinderException e )
-            {
-                throw new QueryExecutionException( "Query '" + toString() + "' could not be executed", e );
-            }
-        }
-
-        @Override
-        public String toString()
-        {
-            return "UnitOfWork( " + moduleUnitOfWork.usecase().name() + " )";
-        }
-    }
-
-    private class ToValuePropertyMappingFunction
-        implements Function<PropertyDescriptor, Object>
-    {
-        private Object entity;
-
-        public ToValuePropertyMappingFunction( Object entity )
-        {
-            this.entity = entity;
-        }
-
-        @Override
-        public Object apply( PropertyDescriptor propertyDescriptor )
-        {
-            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
-            return entityState.propertyValueOf( propertyDescriptor.qualifiedName() );
-        }
-    }
-
-    private class ToValueAssociationMappingFunction<T>
-        implements Function<AssociationDescriptor, EntityReference>
-    {
-        private final T entity;
-
-        public ToValueAssociationMappingFunction( T entity )
-        {
-            this.entity = entity;
-        }
-
-        @Override
-        public EntityReference apply( AssociationDescriptor associationDescriptor )
-        {
-            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
-            return entityState.associationValueOf( associationDescriptor.qualifiedName() );
-        }
-    }
-
-    private class ToValueManyAssociationMappingFunction<T>
-        implements Function<AssociationDescriptor, Iterable<EntityReference>>
-    {
-        private final T entity;
-
-        public ToValueManyAssociationMappingFunction( T entity )
-        {
-            this.entity = entity;
-        }
-
-        @Override
-        public Iterable<EntityReference> apply( AssociationDescriptor associationDescriptor )
-        {
-            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
-            return entityState.manyAssociationValueOf( associationDescriptor.qualifiedName() );
-        }
-    }
-
-    private class ToValueNameAssociationMappingFunction<T>
-        implements Function<AssociationDescriptor, Map<String, EntityReference>>
-    {
-        private final T entity;
-
-        public ToValueNameAssociationMappingFunction( T entity )
-        {
-            this.entity = entity;
-        }
-
-        @Override
-        public Map<String, EntityReference> apply( AssociationDescriptor associationDescriptor )
-        {
-            Map<String, EntityReference> result = new HashMap<>();
-            EntityState entityState = EntityInstance.entityInstanceOf( (EntityComposite) entity ).entityState();
-            final NamedAssociationState state = entityState.namedAssociationValueOf( associationDescriptor.qualifiedName() );
-            for( String name : state )
-            {
-                result.put( name, state.get( name ) );
-            }
-            return result;
-        }
-    }
-
-    private class ToEntityPropertyMappingFunction<T>
-        implements Function<PropertyDescriptor, Object>
-    {
-        private final T value;
-
-        public ToEntityPropertyMappingFunction( T value )
-        {
-            this.value = value;
-        }
-
-        @Override
-        public Object apply( PropertyDescriptor propertyDescriptor )
-        {
-            StateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
-            Property<Object> property = state.propertyFor( propertyDescriptor.accessor() );
-            return property.get();
-        }
-    }
-
-    private class ToEntityAssociationMappingFunction<T>
-        implements Function<AssociationDescriptor, EntityReference>
-    {
-
-        private final T value;
-
-        public ToEntityAssociationMappingFunction( T value )
-        {
-            this.value = value;
-        }
-
-        @Override
-        public EntityReference apply( AssociationDescriptor associationDescriptor )
-        {
-            AssociationStateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
-            AssociationInstance<T> association = (AssociationInstance<T>) state.associationFor( associationDescriptor.accessor() );
-            return association.getAssociationState().get();
-        }
-    }
-
-    private class ToEntityManyAssociationMappingFunction<T>
-        implements Function<AssociationDescriptor, Iterable<EntityReference>>
-    {
-
-        private final T value;
-
-        public ToEntityManyAssociationMappingFunction( T valueComposite )
-        {
-            this.value = valueComposite;
-        }
-
-        @Override
-        public Iterable<EntityReference> apply( AssociationDescriptor associationDescriptor )
-        {
-            AssociationStateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
-            ManyAssociationInstance<T> association =
-                (ManyAssociationInstance<T>) state.manyAssociationFor( associationDescriptor.accessor() );
-            return association.getManyAssociationState();
-        }
-    }
-
-    private class ToEntityNameAssociationMappingFunction<T>
-        implements Function<AssociationDescriptor, Map<String, EntityReference>>
-    {
-        private final T value;
-
-        public ToEntityNameAssociationMappingFunction( T valueComposite )
-        {
-            this.value = valueComposite;
-        }
-
-        @Override
-        public Map<String, EntityReference> apply( AssociationDescriptor associationDescriptor )
-        {
-            AssociationStateHolder state = ValueInstance.valueInstanceOf( (ValueComposite) value ).state();
-            NamedAssociationInstance<T> association =
-                (NamedAssociationInstance<T>) state.namedAssociationFor( associationDescriptor.accessor() );
-            HashMap<String, EntityReference> result = new HashMap<>();
-            for( Map.Entry<String, EntityReference> entry : association.getEntityReferences() )
-            {
-                result.put( entry.getKey(), entry.getValue() );
-            }
-            return result;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookup.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookup.java b/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookup.java
deleted file mode 100755
index 6947b73..0000000
--- a/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookup.java
+++ /dev/null
@@ -1,526 +0,0 @@
-/*
- * Copyright (c) 2008-2012, Rickard Öberg.
- * Copyright (c) 2008-2012, Niclas Hedhman.
- * Copyright (c) 2012, Paul Merlin.
- *
- * Licensed  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.zest.runtime.structure;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.WildcardType;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import org.apache.zest.api.common.Visibility;
-import org.apache.zest.api.composite.AmbiguousTypeException;
-import org.apache.zest.api.composite.ModelDescriptor;
-import org.apache.zest.api.composite.TransientDescriptor;
-import org.apache.zest.api.entity.EntityDescriptor;
-import org.apache.zest.api.object.ObjectDescriptor;
-import org.apache.zest.api.service.NoSuchServiceException;
-import org.apache.zest.api.service.ServiceReference;
-import org.apache.zest.api.type.HasTypes;
-import org.apache.zest.api.value.ValueDescriptor;
-import org.apache.zest.spi.module.ModelModule;
-
-import static java.util.stream.Stream.concat;
-import static org.apache.zest.api.common.Visibility.application;
-import static org.apache.zest.api.common.Visibility.layer;
-import static org.apache.zest.api.common.Visibility.module;
-import static org.apache.zest.api.util.Classes.RAW_CLASS;
-import static org.apache.zest.api.util.Classes.interfacesOf;
-import static org.apache.zest.functional.Iterables.first;
-
-/**
- * Central place for Composite Type lookups.
- */
-public class TypeLookup
-{
-
-    // Constructor parameters
-    private final ModuleInstance moduleInstance;
-    // Eager instance objects
-    private final Map<Class<?>, ModelModule<ObjectDescriptor>> objectModels;
-    private final Map<Class<?>, ModelModule<TransientDescriptor>> transientModels;
-    private final Map<Class<?>, ModelModule<ValueDescriptor>> valueModels;
-    private final Map<Class<?>, List<ModelModule<EntityDescriptor>>> allEntityModels;
-    private final Map<Class<?>, ModelModule<EntityDescriptor>> unambiguousEntityModels;
-    private final Map<Type, ServiceReference<?>> serviceReferences;
-    private final Map<Type, List<ServiceReference<?>>> servicesReferences;
-
-    /**
-     * Create a new TypeLookup bound to the given ModuleInstance.
-     *
-     * @param moduleInstance ModuleInstance bound to this TypeLookup
-     */
-    TypeLookup( ModuleInstance moduleInstance )
-    {
-        // Constructor parameters
-        this.moduleInstance = moduleInstance;
-
-        // Eager instance objects
-        objectModels = new ConcurrentHashMap<>();
-        transientModels = new ConcurrentHashMap<>();
-        valueModels = new ConcurrentHashMap<>();
-        allEntityModels = new ConcurrentHashMap<>();
-        unambiguousEntityModels = new ConcurrentHashMap<>();
-        serviceReferences = new ConcurrentHashMap<>();
-        servicesReferences = new ConcurrentHashMap<>();
-    }
-
-    /**
-     * Lookup first Object Model matching the given Type.
-     *
-     * <p>First, if Object Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Second, if Object Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * @param type Looked up Type
-     *
-     * @return First matching Object Model
-     */
-    ModelModule<ObjectDescriptor> lookupObjectModel( final Class type )
-    {
-        ModelModule<ObjectDescriptor> model = objectModels.get( type );
-        if( model == null )
-        {
-            List<ModelModule<ObjectDescriptor>> allModels = allObjects().collect( Collectors.toList() );
-            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
-            if( model == null )
-            {
-                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
-            }
-            if( model != null )
-            {
-                objectModels.put( type, model );
-            }
-        }
-        return model;
-    }
-
-    /**
-     * Lookup first Transient Model matching the given Type.
-     *
-     * <p>First, if Transient Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Second, if Transient Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * @param type Looked up Type
-     *
-     * @return First matching Transient Model
-     */
-    ModelModule<TransientDescriptor> lookupTransientModel( final Class type )
-    {
-        ModelModule<TransientDescriptor> model = transientModels.get( type );
-        if( model == null )
-        {
-            List<ModelModule<TransientDescriptor>> allModels = allTransients().collect( Collectors.toList() );
-            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
-            if( model == null )
-            {
-                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
-            }
-            if( model != null )
-            {
-                transientModels.put( type, model );
-            }
-        }
-        return model;
-    }
-
-    /**
-     * Lookup first Value Model matching the given Type.
-     *
-     * <p>First, if Value Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Second, if Value Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * @param type Looked up Type
-     *
-     * @return First matching Value Model
-     */
-    public ModelModule<ValueDescriptor> lookupValueModel( final Class type )
-    {
-        ModelModule<ValueDescriptor> model = valueModels.get( type );
-        if( model == null )
-        {
-            List<ModelModule<ValueDescriptor>> allModels = allValues().collect( Collectors.toList() );
-            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
-            if( model == null )
-            {
-                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
-            }
-            if( model != null )
-            {
-                valueModels.put( type, model );
-            }
-        }
-        return model;
-    }
-
-    /**
-     * Lookup first Entity Model matching the given Type.
-     *
-     * <p>First, if Entity Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Second, if Entity Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
-     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * <p><b>Should be used for creational use cases only.</b> For non-creational use cases see
-     * {@link #lookupEntityModels(java.lang.Class)}.</p>
-     *
-     * @param type Looked up Type
-     *
-     * @return First matching Entity Model
-     */
-    ModelModule<EntityDescriptor> lookupEntityModel( final Class type )
-    {
-        ModelModule<EntityDescriptor> model = unambiguousEntityModels.get( type );
-
-        if( model == null )
-        {
-            List<ModelModule<EntityDescriptor>> allModels = allEntities().collect( Collectors.toList() );
-            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
-            if( model == null )
-            {
-                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
-            }
-            if( model != null )
-            {
-                unambiguousEntityModels.put( type, model );
-            }
-        }
-        return model;
-    }
-
-    /**
-     * Lookup all Entity Models matching the given Type.
-     *
-     * <p>Returned Iterable contains, in order, Entity Models that: </p>
-     *
-     * <ul>
-     * <li>exactly match the given type, in Visibility then Assembly order ;</li>
-     * <li>match a type assignable to the given type, in Visibility then Assembly order.</li>
-     * </ul>
-     *
-     * <p>Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
-     * <p>Multiple <b>assignable</b> matches are <b>allowed</b> to enable polymorphic fetches and queries.</p>
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * <p><b>Should be used for non-creational use cases only.</b> For creational use cases see
-     * {@link #lookupEntityModel(java.lang.Class)}.</p>
-     *
-     * @param type Looked up Type
-     *
-     * @return All matching Entity Models
-     */
-    Iterable<ModelModule<EntityDescriptor>> lookupEntityModels( final Class type )
-    {
-        List<ModelModule<EntityDescriptor>> result = allEntityModels.get( type );
-        if( result == null )
-        {
-            result = concat(
-                allEntities().filter( ref -> new ExactTypeMatching<>( type ).test( ref.model() ) ),
-                allEntities().filter( ref -> new AssignableFromTypeMatching<>( type ).test( ref.model() ) )
-            ).distinct().collect( Collectors.toList() );
-            allEntityModels.put( type, result );
-        }
-        return result;
-    }
-
-    /**
-     * Lookup first ServiceReference matching the given Type.
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * <p>See {@link #lookupServiceReferences(Type)}.</p>
-     *
-     * @param <T>         Service Type
-     * @param serviceType Looked up Type
-     *
-     * @return First matching ServiceReference
-     */
-    <T> ServiceReference<T> lookupServiceReference( Type serviceType )
-    {
-        @SuppressWarnings( "unchecked" )
-        ServiceReference<T> serviceReference = (ServiceReference<T>) serviceReferences.get( serviceType );
-        if( serviceReference == null )
-        {
-            // Lazily resolve ServiceReference
-            serviceReference = first( lookupServiceReferences( serviceType ) );
-            if( serviceReference != null )
-            {
-                serviceReferences.put( serviceType, serviceReference );
-            }
-        }
-
-        if( serviceReference == null )
-        {
-            throw new NoSuchServiceException( RAW_CLASS.apply( serviceType ).getName(), moduleInstance.name() );
-        }
-        return serviceReference;
-    }
-
-    /**
-     * Lookup all ServiceReferences matching the given Type.
-     *
-     * <p>Returned Iterable contains, in order, ServiceReferences that: </p>
-     *
-     * <ul>
-     * <li>exactly match the given type, in Visibility then Assembly order ;</li>
-     * <li>match a type assignable to the given type, in Visibility then Assembly order.</li>
-     * </ul>
-     *
-     * <p>Multiple <b>exact</b> matches with the same Visibility are <b>allowed</b> to enable polymorphic lookup/injection.</p>
-     * <p>Multiple <b>assignable</b> matches with the same Visibility are <b>allowed</b> for the very same reason.</p>
-     *
-     * <p>Type lookup is done lazily and cached.</p>
-     *
-     * @param <T>  Service Type
-     * @param type Looked up Type
-     *
-     * @return All matching ServiceReferences
-     */
-    <T> List<ServiceReference<T>> lookupServiceReferences( final Type type )
-    {
-        List<ServiceReference<?>> serviceRefs = servicesReferences.get( type );
-        if( serviceRefs == null )
-        {
-            serviceRefs = concat(
-                allServices()
-                    .filter( new ExactTypeMatching<>( type  ) ),
-                allServices()
-                    .filter( new AssignableFromTypeMatching<>( type )
-                    )
-            ).distinct().collect( Collectors.toList() );
-            servicesReferences.put( type, serviceRefs );
-        }
-        List<ServiceReference<T>> result = new ArrayList<>();
-        //noinspection unchecked
-        serviceRefs.forEach( ref -> result.add( (ServiceReference<T>) ref ) );
-        return result;
-    }
-
-    public Stream<Class<?>> allVisibleObjects()
-    {
-        return allObjects().flatMap( model -> model.model().types() );
-    }
-
-    private Stream<ModelModule<ObjectDescriptor>> allObjects()
-    {
-        return concat( moduleInstance.visibleObjects( module ),
-                       concat(
-                           moduleInstance.layerInstance().visibleObjects( layer ),
-                           concat(
-                               moduleInstance.layerInstance().visibleObjects( application ),
-                               moduleInstance.layerInstance().usedLayersInstance().visibleObjects()
-                           )
-                       )
-        );
-    }
-
-    private Stream<ModelModule<TransientDescriptor>> allTransients()
-    {
-        return concat( moduleInstance.visibleTransients( module ),
-                       concat(
-                           moduleInstance.layerInstance().visibleTransients( layer ),
-                           concat(
-                               moduleInstance.layerInstance().visibleTransients( application ),
-                               moduleInstance.layerInstance().usedLayersInstance().visibleTransients()
-                           )
-                       )
-        );
-    }
-
-    private Stream<ModelModule<ValueDescriptor>> allValues()
-    {
-        return concat( moduleInstance.visibleValues( module ),
-                       concat(
-                           moduleInstance.layerInstance().visibleValues( layer ),
-                           concat(
-                               moduleInstance.layerInstance().visibleValues( application ),
-                               moduleInstance.layerInstance().usedLayersInstance().visibleValues()
-                           )
-                       )
-        );
-    }
-
-    private Stream<ModelModule<EntityDescriptor>> allEntities()
-    {
-        return concat( moduleInstance.visibleEntities( module ),
-                       concat(
-                           moduleInstance.layerInstance().visibleEntities( layer ),
-                           concat(
-                               moduleInstance.layerInstance().visibleEntities( application ),
-                               moduleInstance.layerInstance().usedLayersInstance().visibleEntities()
-                           )
-                       )
-        );
-    }
-
-    private Stream<ServiceReference<?>> allServices()
-    {
-        return concat( moduleInstance.visibleServices( module ),
-                       concat(
-                           moduleInstance.layerInstance().visibleServices( layer ),
-                           concat(
-                               moduleInstance.layerInstance().visibleServices( application ),
-                               moduleInstance.layerInstance().usedLayersInstance().visibleServices()
-                           )
-                       )
-        );
-    }
-
-    private <T extends ModelDescriptor> ModelModule<T> ambiguityMatching(
-        Class type,
-        List<ModelModule<T>> modelModules,
-        TypeMatching<T> matching
-    )
-    {
-        List<ModelModule<T>> models = modelModules.stream()
-            .filter( ref -> matching.test( ref.model() ) )
-            .filter( new SameVisibility<>() )
-            .distinct()
-            .collect( Collectors.toList() );
-
-        if( models.size() > 1 )
-        {
-            throw new AmbiguousTypeException( "More than one type matches " + type.getName() + ": " + models + "]" );
-        }
-        if( models.isEmpty() )
-        {
-            return null;
-        }
-        return models.get( 0 );
-    }
-
-    private static abstract class TypeMatching<T extends HasTypes>
-        implements Predicate<T>
-    {
-        protected final Type lookedUpType;
-
-        protected TypeMatching( Type lookedUpType )
-        {
-            this.lookedUpType = lookedUpType;
-        }
-
-        @Override
-        public final boolean test( T model )
-        {
-            if( lookedUpType instanceof Class )
-            {
-                return model.types().anyMatch( checkMatch( lookedUpType ) );
-            }
-            else
-            {
-                if( lookedUpType instanceof ParameterizedType )
-                {
-                    // Foo<Bar> check
-                    // First check Foo
-                    ParameterizedType parameterizedType = (ParameterizedType) lookedUpType;
-                    Type rawType = parameterizedType.getRawType();
-                    if( !model.types().anyMatch( checkMatch( rawType ) ) )
-                    {
-                        return false;
-                    }
-                    // Then check Bar
-                    return interfacesOf( model.types() ).anyMatch( intf -> intf.equals( lookedUpType ) );
-                }
-                else if( lookedUpType instanceof WildcardType )
-                {
-                    return true;
-                }
-                return false;
-            }
-        }
-
-        protected abstract Predicate<Type> checkMatch( Type matchTo );
-    }
-
-    private static final class ExactTypeMatching<T extends HasTypes> extends TypeMatching<T>
-    {
-        private ExactTypeMatching( Type lookedUpType )
-        {
-            super( lookedUpType );
-        }
-
-        protected Predicate<Type> checkMatch( Type matchTo )
-        {
-            return matchTo::equals;
-        }
-    }
-
-    private static final class AssignableFromTypeMatching<T extends HasTypes> extends TypeMatching<T>
-    {
-        private AssignableFromTypeMatching( Type lookedUpType )
-        {
-            super( lookedUpType );
-        }
-
-        protected Predicate<Type> checkMatch( Type matchTo )
-        {
-            // TODO; what to do if there is ParameterizedType here?? Now set to ClassCastException and see if anything surfaces
-//            if( matchTo instanceof Class )
-            {
-                Class<?> clazz = (Class<?>) matchTo;
-                return candidate ->
-                    !candidate.equals( matchTo ) && clazz.isAssignableFrom( (Class<?>) candidate );
-            }
-//            return candidate -> candidate.equals( matchTo );
-        }
-    }
-
-    /**
-     * This Predicate will filter out all Models that doesn't have the same visisbility as the first one.
-     */
-    private class SameVisibility<T extends ModelDescriptor>
-        implements Predicate<ModelModule<T>>
-    {
-        private Visibility current = null;
-
-        @Override
-        public boolean test( ModelModule<T> model )
-        {
-            if( current == null )
-            {
-                current = model.model().visibility();
-                return true;
-            }
-            return current == model.model().visibility();
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookupImpl.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookupImpl.java b/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookupImpl.java
new file mode 100755
index 0000000..7835aaa
--- /dev/null
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/structure/TypeLookupImpl.java
@@ -0,0 +1,538 @@
+/*
+ * Copyright (c) 2008-2012, Rickard Öberg.
+ * Copyright (c) 2008-2012, Niclas Hedhman.
+ * Copyright (c) 2012, Paul Merlin.
+ *
+ * Licensed  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.zest.runtime.structure;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.WildcardType;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.zest.api.common.Visibility;
+import org.apache.zest.api.composite.AmbiguousTypeException;
+import org.apache.zest.api.composite.ModelDescriptor;
+import org.apache.zest.api.composite.TransientDescriptor;
+import org.apache.zest.api.entity.EntityDescriptor;
+import org.apache.zest.api.object.ObjectDescriptor;
+import org.apache.zest.api.service.NoSuchServiceException;
+import org.apache.zest.api.service.ServiceReference;
+import org.apache.zest.api.type.HasTypes;
+import org.apache.zest.api.value.ValueDescriptor;
+import org.apache.zest.spi.structure.ModelModule;
+import org.apache.zest.spi.structure.TypeLookup;
+
+import static java.util.stream.Stream.concat;
+import static org.apache.zest.api.common.Visibility.application;
+import static org.apache.zest.api.common.Visibility.layer;
+import static org.apache.zest.api.common.Visibility.module;
+import static org.apache.zest.api.util.Classes.RAW_CLASS;
+import static org.apache.zest.api.util.Classes.interfacesOf;
+import static org.apache.zest.functional.Iterables.first;
+
+/**
+ * Central place for Composite Type lookups.
+ */
+public class TypeLookupImpl
+    implements TypeLookup
+{
+
+    // Constructor parameters
+    private final ModuleInstance moduleInstance;
+    // Eager instance objects
+    private final Map<Class<?>, ModelModule<ObjectDescriptor>> objectModels;
+    private final Map<Class<?>, ModelModule<TransientDescriptor>> transientModels;
+    private final Map<Class<?>, ModelModule<ValueDescriptor>> valueModels;
+    private final Map<Class<?>, List<ModelModule<EntityDescriptor>>> allEntityModels;
+    private final Map<Class<?>, ModelModule<EntityDescriptor>> unambiguousEntityModels;
+    private final Map<Type, ServiceReference<?>> serviceReferences;
+    private final Map<Type, List<ServiceReference<?>>> servicesReferences;
+
+    /**
+     * Create a new TypeLookup bound to the given ModuleInstance.
+     *
+     * @param moduleInstance ModuleInstance bound to this TypeLookup
+     */
+    TypeLookupImpl( ModuleInstance moduleInstance )
+    {
+        // Constructor parameters
+        this.moduleInstance = moduleInstance;
+
+        // Eager instance objects
+        objectModels = new ConcurrentHashMap<>();
+        transientModels = new ConcurrentHashMap<>();
+        valueModels = new ConcurrentHashMap<>();
+        allEntityModels = new ConcurrentHashMap<>();
+        unambiguousEntityModels = new ConcurrentHashMap<>();
+        serviceReferences = new ConcurrentHashMap<>();
+        servicesReferences = new ConcurrentHashMap<>();
+    }
+
+    /**
+     * Lookup first Object Model matching the given Type.
+     *
+     * <p>First, if Object Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Second, if Object Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return First matching Object Model
+     */
+    ModelModule<ObjectDescriptor> lookupObjectModel( final Class type )
+    {
+        ModelModule<ObjectDescriptor> model = objectModels.get( type );
+        if( model == null )
+        {
+            List<ModelModule<ObjectDescriptor>> allModels = allObjects().collect( Collectors.toList() );
+            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
+            if( model == null )
+            {
+                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
+            }
+            if( model != null )
+            {
+                objectModels.put( type, model );
+            }
+        }
+        return model;
+    }
+
+    /**
+     * Lookup first Transient Model matching the given Type.
+     *
+     * <p>First, if Transient Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Second, if Transient Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return First matching Transient Model
+     */
+    ModelModule<TransientDescriptor> lookupTransientModel( final Class type )
+    {
+        ModelModule<TransientDescriptor> model = transientModels.get( type );
+        if( model == null )
+        {
+            List<ModelModule<TransientDescriptor>> allModels = allTransients().collect( Collectors.toList() );
+            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
+            if( model == null )
+            {
+                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
+            }
+            if( model != null )
+            {
+                transientModels.put( type, model );
+            }
+        }
+        return model;
+    }
+
+    /**
+     * Lookup first Value Model matching the given Type.
+     *
+     * <p>First, if Value Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Second, if Value Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return First matching Value Model
+     */
+    public ModelModule<ValueDescriptor> lookupValueModel( final Class type )
+    {
+        ModelModule<ValueDescriptor> model = valueModels.get( type );
+        if( model == null )
+        {
+            List<ModelModule<ValueDescriptor>> allModels = allValues().collect( Collectors.toList() );
+            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
+            if( model == null )
+            {
+                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
+            }
+            if( model != null )
+            {
+                valueModels.put( type, model );
+            }
+        }
+        return model;
+    }
+
+    /**
+     * Lookup first Entity Model matching the given Type.
+     *
+     * <p>First, if Entity Models exactly match the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Second, if Entity Models match a type assignable to the given type, the closest one (Visibility then Assembly order) is returned.
+     * Multiple <b>assignable</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * <p><b>Should be used for creational use cases only.</b> For non-creational use cases see
+     * {@link #lookupEntityModels(java.lang.Class)}.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return First matching Entity Model
+     */
+    @Override
+    public ModelModule<EntityDescriptor> lookupEntityModel( final Class type )
+    {
+        ModelModule<EntityDescriptor> model = unambiguousEntityModels.get( type );
+
+        if( model == null )
+        {
+            List<ModelModule<EntityDescriptor>> allModels = allEntities().collect( Collectors.toList() );
+            model = ambiguityMatching( type, allModels, new ExactTypeMatching<>( type ) );
+            if( model == null )
+            {
+                model = ambiguityMatching( type, allModels, new AssignableFromTypeMatching<>( type ) );
+            }
+            if( model != null )
+            {
+                unambiguousEntityModels.put( type, model );
+            }
+        }
+        return model;
+    }
+
+    /**
+     * Lookup all Entity Models matching the given Type.
+     *
+     * <p>Returned Iterable contains, in order, Entity Models that: </p>
+     *
+     * <ul>
+     * <li>exactly match the given type, in Visibility then Assembly order ;</li>
+     * <li>match a type assignable to the given type, in Visibility then Assembly order.</li>
+     * </ul>
+     *
+     * <p>Multiple <b>exact</b> matches with the same Visibility are <b>forbidden</b> and result in an AmbiguousTypeException.</p>
+     * <p>Multiple <b>assignable</b> matches are <b>allowed</b> to enable polymorphic fetches and queries.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * <p><b>Should be used for non-creational use cases only.</b> For creational use cases see
+     * {@link #lookupEntityModel(java.lang.Class)}.</p>
+     *
+     * @param type Looked up Type
+     *
+     * @return All matching Entity Models
+     */
+    @Override
+    public Iterable<ModelModule<EntityDescriptor>> lookupEntityModels( final Class type )
+    {
+        List<ModelModule<EntityDescriptor>> result = allEntityModels.get( type );
+        if( result == null )
+        {
+            result = concat(
+                allEntities().filter( ref -> new ExactTypeMatching<>( type ).test( ref.model() ) ),
+                allEntities().filter( ref -> new AssignableFromTypeMatching<>( type ).test( ref.model() ) )
+            ).distinct().collect( Collectors.toList() );
+            allEntityModels.put( type, result );
+        }
+        return result;
+    }
+
+    /**
+     * Lookup first ServiceReference matching the given Type.
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * <p>See {@link #lookupServiceReferences(Type)}.</p>
+     *
+     * @param <T>         Service Type
+     * @param serviceType Looked up Type
+     *
+     * @return First matching ServiceReference
+     */
+    @Override
+    public <T> ServiceReference<T> lookupServiceReference( Type serviceType )
+    {
+        @SuppressWarnings( "unchecked" )
+        ServiceReference<T> serviceReference = (ServiceReference<T>) serviceReferences.get( serviceType );
+        if( serviceReference == null )
+        {
+            // Lazily resolve ServiceReference
+            serviceReference = first( lookupServiceReferences( serviceType ) );
+            if( serviceReference != null )
+            {
+                serviceReferences.put( serviceType, serviceReference );
+            }
+        }
+
+        if( serviceReference == null )
+        {
+            throw new NoSuchServiceException( RAW_CLASS.apply( serviceType ).getName(), moduleInstance.name() );
+        }
+        return serviceReference;
+    }
+
+    /**
+     * Lookup all ServiceReferences matching the given Type.
+     *
+     * <p>Returned Iterable contains, in order, ServiceReferences that: </p>
+     *
+     * <ul>
+     * <li>exactly match the given type, in Visibility then Assembly order ;</li>
+     * <li>match a type assignable to the given type, in Visibility then Assembly order.</li>
+     * </ul>
+     *
+     * <p>Multiple <b>exact</b> matches with the same Visibility are <b>allowed</b> to enable polymorphic lookup/injection.</p>
+     * <p>Multiple <b>assignable</b> matches with the same Visibility are <b>allowed</b> for the very same reason.</p>
+     *
+     * <p>Type lookup is done lazily and cached.</p>
+     *
+     * @param <T>  Service Type
+     * @param type Looked up Type
+     *
+     * @return All matching ServiceReferences
+     */
+    @Override
+    public <T> List<ServiceReference<T>> lookupServiceReferences( final Type type )
+    {
+        List<ServiceReference<?>> serviceRefs = servicesReferences.get( type );
+        if( serviceRefs == null )
+        {
+            serviceRefs = concat(
+                allServices()
+                    .filter( new ExactTypeMatching<>( type  ) ),
+                allServices()
+                    .filter( new AssignableFromTypeMatching<>( type )
+                    )
+            ).distinct().collect( Collectors.toList() );
+            servicesReferences.put( type, serviceRefs );
+        }
+        List<ServiceReference<T>> result = new ArrayList<>();
+        //noinspection unchecked
+        serviceRefs.forEach( ref -> result.add( (ServiceReference<T>) ref ) );
+        return result;
+    }
+
+    @Override
+    public Stream<Class<?>> allVisibleObjects()
+    {
+        return allObjects().flatMap( model -> model.model().types() );
+    }
+
+    @Override
+    public Stream<ModelModule<ObjectDescriptor>> allObjects()
+    {
+        return concat( moduleInstance.visibleObjects( module ),
+                       concat(
+                           moduleInstance.layerInstance().visibleObjects( layer ),
+                           concat(
+                               moduleInstance.layerInstance().visibleObjects( application ),
+                               moduleInstance.layerInstance().usedLayersInstance().visibleObjects()
+                           )
+                       )
+        );
+    }
+
+    @Override
+    public Stream<ModelModule<TransientDescriptor>> allTransients()
+    {
+        return concat( moduleInstance.visibleTransients( module ),
+                       concat(
+                           moduleInstance.layerInstance().visibleTransients( layer ),
+                           concat(
+                               moduleInstance.layerInstance().visibleTransients( application ),
+                               moduleInstance.layerInstance().usedLayersInstance().visibleTransients()
+                           )
+                       )
+        );
+    }
+
+    @Override
+    public Stream<ModelModule<ValueDescriptor>> allValues()
+    {
+        return concat( moduleInstance.visibleValues( module ),
+                       concat(
+                           moduleInstance.layerInstance().visibleValues( layer ),
+                           concat(
+                               moduleInstance.layerInstance().visibleValues( application ),
+                               moduleInstance.layerInstance().usedLayersInstance().visibleValues()
+                           )
+                       )
+        );
+    }
+
+    @Override
+    public Stream<ModelModule<EntityDescriptor>> allEntities()
+    {
+        return concat( moduleInstance.visibleEntities( module ),
+                       concat(
+                           moduleInstance.layerInstance().visibleEntities( layer ),
+                           concat(
+                               moduleInstance.layerInstance().visibleEntities( application ),
+                               moduleInstance.layerInstance().usedLayersInstance().visibleEntities()
+                           )
+                       )
+        );
+    }
+
+    @Override
+    public Stream<ServiceReference<?>> allServices()
+    {
+        return concat( moduleInstance.visibleServices( module ),
+                       concat(
+                           moduleInstance.layerInstance().visibleServices( layer ),
+                           concat(
+                               moduleInstance.layerInstance().visibleServices( application ),
+                               moduleInstance.layerInstance().usedLayersInstance().visibleServices()
+                           )
+                       )
+        );
+    }
+
+    private <T extends ModelDescriptor> ModelModule<T> ambiguityMatching(
+        Class type,
+        List<ModelModule<T>> modelModules,
+        TypeMatching<T> matching
+    )
+    {
+        List<ModelModule<T>> models = modelModules.stream()
+            .filter( ref -> matching.test( ref.model() ) )
+            .filter( new SameVisibility<>() )
+            .distinct()
+            .collect( Collectors.toList() );
+
+        if( models.size() > 1 )
+        {
+            throw new AmbiguousTypeException( "More than one type matches " + type.getName() + ": " + models + "]" );
+        }
+        if( models.isEmpty() )
+        {
+            return null;
+        }
+        return models.get( 0 );
+    }
+
+    private static abstract class TypeMatching<T extends HasTypes>
+        implements Predicate<T>
+    {
+        protected final Type lookedUpType;
+
+        protected TypeMatching( Type lookedUpType )
+        {
+            this.lookedUpType = lookedUpType;
+        }
+
+        @Override
+        public final boolean test( T model )
+        {
+            if( lookedUpType instanceof Class )
+            {
+                return model.types().anyMatch( checkMatch( lookedUpType ) );
+            }
+            else
+            {
+                if( lookedUpType instanceof ParameterizedType )
+                {
+                    // Foo<Bar> check
+                    // First check Foo
+                    ParameterizedType parameterizedType = (ParameterizedType) lookedUpType;
+                    Type rawType = parameterizedType.getRawType();
+                    if( !model.types().anyMatch( checkMatch( rawType ) ) )
+                    {
+                        return false;
+                    }
+                    // Then check Bar
+                    return interfacesOf( model.types() ).anyMatch( intf -> intf.equals( lookedUpType ) );
+                }
+                else if( lookedUpType instanceof WildcardType )
+                {
+                    return true;
+                }
+                return false;
+            }
+        }
+
+        protected abstract Predicate<Type> checkMatch( Type matchTo );
+    }
+
+    private static final class ExactTypeMatching<T extends HasTypes> extends TypeMatching<T>
+    {
+        private ExactTypeMatching( Type lookedUpType )
+        {
+            super( lookedUpType );
+        }
+
+        protected Predicate<Type> checkMatch( Type matchTo )
+        {
+            return matchTo::equals;
+        }
+    }
+
+    private static final class AssignableFromTypeMatching<T extends HasTypes> extends TypeMatching<T>
+    {
+        private AssignableFromTypeMatching( Type lookedUpType )
+        {
+            super( lookedUpType );
+        }
+
+        protected Predicate<Type> checkMatch( Type matchTo )
+        {
+            // TODO; what to do if there is ParameterizedType here?? Now set to ClassCastException and see if anything surfaces
+//            if( matchTo instanceof Class )
+            {
+                Class<?> clazz = (Class<?>) matchTo;
+                return candidate ->
+                    !candidate.equals( matchTo ) && clazz.isAssignableFrom( (Class<?>) candidate );
+            }
+//            return candidate -> candidate.equals( matchTo );
+        }
+    }
+
+    /**
+     * This Predicate will filter out all Models that doesn't have the same visisbility as the first one.
+     */
+    private class SameVisibility<T extends ModelDescriptor>
+        implements Predicate<ModelModule<T>>
+    {
+        private Visibility current = null;
+
+        @Override
+        public boolean test( ModelModule<T> model )
+        {
+            if( current == null )
+            {
+                current = model.model().visibility();
+                return true;
+            }
+            return current == model.model().visibility();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/structure/UsedLayersInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/structure/UsedLayersInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/structure/UsedLayersInstance.java
index 5a9bc94..ebf4b9c 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/structure/UsedLayersInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/structure/UsedLayersInstance.java
@@ -17,13 +17,12 @@ package org.apache.zest.runtime.structure;
 import java.util.List;
 import java.util.stream.Stream;
 import org.apache.zest.api.common.Visibility;
-import org.apache.zest.api.composite.ModelDescriptor;
 import org.apache.zest.api.composite.TransientDescriptor;
 import org.apache.zest.api.entity.EntityDescriptor;
 import org.apache.zest.api.object.ObjectDescriptor;
 import org.apache.zest.api.service.ServiceReference;
 import org.apache.zest.api.value.ValueDescriptor;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 
 /**
  * JAVADOC

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityBuilderInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityBuilderInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityBuilderInstance.java
index 425e851..ed8d137 100755
--- a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityBuilderInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityBuilderInstance.java
@@ -25,8 +25,7 @@ import org.apache.zest.api.entity.LifecycleException;
 import org.apache.zest.runtime.composite.FunctionStateResolver;
 import org.apache.zest.runtime.entity.EntityInstance;
 import org.apache.zest.runtime.entity.EntityModel;
-import org.apache.zest.spi.module.ModelModule;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.entity.EntityState;
 import org.apache.zest.spi.entitystore.EntityStoreUnitOfWork;
 import org.apache.zest.spi.module.ModuleSpi;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityFunction.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityFunction.java b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityFunction.java
new file mode 100644
index 0000000..a7524db
--- /dev/null
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/unitofwork/EntityFunction.java
@@ -0,0 +1,46 @@
+/*
+ * 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.zest.runtime.unitofwork;
+
+import java.lang.reflect.Type;
+import java.util.function.BiFunction;
+import org.apache.zest.api.entity.EntityReference;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+
+import static org.apache.zest.api.util.Classes.RAW_CLASS;
+
+public class EntityFunction
+    implements BiFunction<EntityReference, Type, Object>
+{
+
+    private final UnitOfWorkFactory uowf;
+
+    public EntityFunction( UnitOfWorkFactory uowf )
+    {
+        this.uowf = uowf;
+    }
+
+    @Override
+    public Object apply( EntityReference entityReference, Type type )
+    {
+        return uowf.currentUnitOfWork().get( RAW_CLASS.apply( type ), entityReference.identity() );
+    }
+}


[2/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestAssembler.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestAssembler.java b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestAssembler.java
index 65120c9..90ea8a0 100644
--- a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestAssembler.java
+++ b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestAssembler.java
@@ -66,10 +66,10 @@ import static org.apache.zest.api.structure.Application.Mode.test;
  */
 @SuppressWarnings( "unchecked" )
 public class TestAssembler
-      implements ApplicationAssembler
+    implements ApplicationAssembler
 {
     public ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
-          throws AssemblyException
+        throws AssemblyException
     {
         // Application assembly
         ApplicationAssembly assembly = applicationFactory.newApplicationAssembly();
@@ -85,17 +85,17 @@ public class TestAssembler
 
         // Layer dependencies
         bootstrapLayer.uses(
-              contextLayer,
-              domainLayer,
-              infrastructureLayer );
+            contextLayer,
+            domainLayer,
+            infrastructureLayer );
 
         contextLayer.uses(
-              domainLayer,
-              infrastructureLayer );
+            domainLayer,
+            infrastructureLayer );
 
         domainLayer.uses(
-              contextLayer,
-              infrastructureLayer
+            contextLayer,
+            infrastructureLayer
         );
 
         // Assemble
@@ -107,120 +107,125 @@ public class TestAssembler
         return assembly;
     }
 
-    private void assembleBootstrapLayer( LayerAssembly bootstrapLayer ) throws AssemblyException
+    private void assembleBootstrapLayer( LayerAssembly bootstrapLayer )
+        throws AssemblyException
     {
-        ModuleAssembly bootstrapModule = bootstrapLayer.module( "BOOTSTRAP-Bootstrap" );
+        ModuleAssembly bootstrapModule = bootstrapLayer.module( "BOOTSTRAP-Bootstrap" ).withDefaultUnitOfWorkFactory();
 
         // Load base data on startup
         bootstrapModule
-              .addServices(
-                    BaseDataService.class )
-              .visibleIn( application )
-              .instantiateOnStartup();
+            .addServices(
+                BaseDataService.class )
+            .visibleIn( application )
+            .instantiateOnStartup();
     }
 
-    private void assembleContextLayer( LayerAssembly contextLayer ) throws AssemblyException
+    private void assembleContextLayer( LayerAssembly contextLayer )
+        throws AssemblyException
     {
         // Role-playing entities
-        ModuleAssembly entityRoleModule = contextLayer.module( "CONTEXT-EntityRole" );
+        ModuleAssembly entityRoleModule = contextLayer.module( "CONTEXT-EntityRole" ).withDefaultUnitOfWorkFactory();
         entityRoleModule
-              .entities(
-                    CargoRoleMap.class,
-                    CargosRoleMap.class,
-                    HandlingEventRoleMap.class,
-                    HandlingEventsRoleMap.class )
-              .visibleIn( application );
-
+            .entities(
+                CargoRoleMap.class,
+                CargosRoleMap.class,
+                HandlingEventRoleMap.class,
+                HandlingEventsRoleMap.class )
+            .visibleIn( application );
 
         // Role-playing values
-        ModuleAssembly valueRoleModule = contextLayer.module( "CONTEXT-ValueRole" );
+        ModuleAssembly valueRoleModule = contextLayer.module( "CONTEXT-ValueRole" ).withDefaultUnitOfWorkFactory();
         valueRoleModule
-              .values(
-                    ItineraryRoleMap.class,
-                    RouteSpecificationRoleMap.class )
-              .visibleIn( application );
-
+            .values(
+                ItineraryRoleMap.class,
+                RouteSpecificationRoleMap.class )
+            .visibleIn( application );
 
-        ModuleAssembly contextSupportModule = contextLayer.module( "CONTEXT-ContextSupport" );
+        ModuleAssembly contextSupportModule = contextLayer.module( "CONTEXT-ContextSupport" )
+            .withDefaultUnitOfWorkFactory();
         contextSupportModule
-              .addServices(
-                    RoutingService.class,
-                    ApplicationEvents.class )
-              .visibleIn( application );
+            .addServices(
+                RoutingService.class,
+                ApplicationEvents.class )
+            .visibleIn( application );
 
         contextSupportModule
-              .values(
-                    RegisterHandlingEventAttemptDTO.class )
-              .visibleIn( application );
+            .values(
+                RegisterHandlingEventAttemptDTO.class )
+            .visibleIn( application );
     }
 
-    private void assembleDomainLayer( LayerAssembly domainLayer ) throws AssemblyException
+    private void assembleDomainLayer( LayerAssembly domainLayer )
+        throws AssemblyException
     {
         // Non-role-playing entities
-        ModuleAssembly entityModule = domainLayer.module( "DOMAIN-Entity" );
+        ModuleAssembly entityModule = domainLayer.module( "DOMAIN-Entity" ).withDefaultUnitOfWorkFactory();
         entityModule
-              .entities(
-                    LocationEntity.class,
-                    VoyageEntity.class )
-              .visibleIn( application );
-
+            .entities(
+                LocationEntity.class,
+                VoyageEntity.class )
+            .visibleIn( application );
 
         // Non-role-playing values
-        ModuleAssembly dataModule = domainLayer.module( "DOMAIN-Data" );
+        ModuleAssembly dataModule = domainLayer.module( "DOMAIN-Data" ).withDefaultUnitOfWorkFactory();
         dataModule
-              .values(
-                    TrackingId.class,
-                    Delivery.class,
-                    ExpectedHandlingEvent.class,
-                    UnLocode.class,
-                    Leg.class,
-                    CarrierMovement.class,
-                    Schedule.class,
-                    VoyageNumber.class )
-              .visibleIn( application );
+            .values(
+                TrackingId.class,
+                Delivery.class,
+                ExpectedHandlingEvent.class,
+                UnLocode.class,
+                Leg.class,
+                CarrierMovement.class,
+                Schedule.class,
+                VoyageNumber.class )
+            .visibleIn( application );
     }
 
-    private void assembleInfrastructureLayer( LayerAssembly infrastructureLayer ) throws AssemblyException
+    private void assembleInfrastructureLayer( LayerAssembly infrastructureLayer )
+        throws AssemblyException
     {
-        ModuleAssembly serializationModule = infrastructureLayer.module( "INFRASTRUCTURE-Serialization" );
+        ModuleAssembly serializationModule = infrastructureLayer.module( "INFRASTRUCTURE-Serialization" )
+            .withDefaultUnitOfWorkFactory();
         serializationModule
             .services( OrgJsonValueSerializationService.class )
             .taggedWith( ValueSerialization.Formats.JSON )
             .setMetaInfo( new Function<Application, Module>()
-        {
-            @Override
-            public Module apply( Application application )
             {
-                return application.findModule( "CONTEXT", "CONTEXT-ContextSupport" );
-            }
-        } )
-        .visibleIn( application );
-
-        ModuleAssembly indexingModule = infrastructureLayer.module( "INFRASTRUCTURE-Indexing" );
+                @Override
+                public Module apply( Application application )
+                {
+                    return application.findModule( "CONTEXT", "CONTEXT-ContextSupport" );
+                }
+            } )
+            .visibleIn( application );
+
+        ModuleAssembly indexingModule = infrastructureLayer.module( "INFRASTRUCTURE-Indexing" )
+            .withDefaultUnitOfWorkFactory();
         indexingModule
-              .objects(
-                    EntityStateSerializer.class,
-                    EntityTypeSerializer.class );
+            .objects(
+                EntityStateSerializer.class,
+                EntityTypeSerializer.class );
 
         indexingModule
-              .addServices(
-                    MemoryRepositoryService.class,
-                    RdfIndexingEngineService.class )
-              .visibleIn( application );
-
+            .addServices(
+                MemoryRepositoryService.class,
+                RdfIndexingEngineService.class )
+            .visibleIn( application );
 
-        ModuleAssembly entityStoreModule = infrastructureLayer.module( "INFRASTRUCTURE-EntityStore" );
+        ModuleAssembly entityStoreModule = infrastructureLayer.module( "INFRASTRUCTURE-EntityStore" )
+            .withDefaultUnitOfWorkFactory();
         entityStoreModule
-              .addServices(
-                    MemoryEntityStoreService.class,
-                    UuidIdentityGeneratorService.class )
-              .visibleIn( application );
+            .addServices(
+                MemoryEntityStoreService.class,
+                UuidIdentityGeneratorService.class )
+            .visibleIn( application );
 
-        ModuleAssembly externalServiceModule = infrastructureLayer.module( "INFRASTRUCTURE-ExternalService" );
+        ModuleAssembly externalServiceModule = infrastructureLayer.module( "INFRASTRUCTURE-ExternalService" )
+            .withDefaultUnitOfWorkFactory();
         externalServiceModule
-              .importedServices(
-                    GraphTraversalService.class )
-              .setMetaInfo( new GraphTraversalServiceImpl( new GraphDAO() ) )
-              .visibleIn( application );
+            .importedServices(
+                GraphTraversalService.class )
+            .setMetaInfo( new GraphTraversalServiceImpl( new GraphDAO() ) )
+            .visibleIn( application );
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BookNewCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BookNewCargoTest.java b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BookNewCargoTest.java
index 66974bf..236f48d 100644
--- a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BookNewCargoTest.java
+++ b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BookNewCargoTest.java
@@ -19,6 +19,7 @@ package org.apache.zest.sample.dcicargo.sample_a.context.shipping.booking;
 
 import java.util.Date;
 import java.util.List;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.unitofwork.UnitOfWork;
@@ -52,19 +53,20 @@ public class BookNewCargoTest
 {
 
     private static final Date TODAY = new Date();
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void prepareTest()
         throws Exception
     {
         super.prepareTest();
-
+        uowf = module.unitOfWorkFactory();
     }
 
     @Test( expected = RouteException.class )
     public void deviation2a_OriginAndDestinationSame() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
         new BookNewCargo( CARGOS, HONGKONG, HONGKONG, day( 17 ) ).book();
@@ -73,7 +75,7 @@ public class BookNewCargoTest
     @Test( expected = RouteException.class )
     public void deviation_2b_1_DeadlineInThePastNotAccepted() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
@@ -83,7 +85,7 @@ public class BookNewCargoTest
     @Test( expected = RouteException.class )
     public void deviation_2b_2_DeadlineTodayIsTooEarly() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
@@ -93,7 +95,7 @@ public class BookNewCargoTest
     @Test
     public void deviation_2b_3_DeadlineTomorrowIsOkay() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
@@ -103,7 +105,7 @@ public class BookNewCargoTest
     @Test
     public void step_2_CreateNewCargo() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
@@ -143,7 +145,7 @@ public class BookNewCargoTest
     @Test( expected = FoundNoRoutesException.class )
     public void deviation_3a_NoRoutesCanBeThatFast() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
@@ -157,7 +159,7 @@ public class BookNewCargoTest
     @Test
     public void step_3_CalculatePossibleRoutes() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
@@ -187,7 +189,7 @@ public class BookNewCargoTest
     @Test
     public void step_5_AssignCargoToRoute() throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         Location STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BuildDeliverySnapshotTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BuildDeliverySnapshotTest.java b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BuildDeliverySnapshotTest.java
index 30c91f9..2277e71 100644
--- a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BuildDeliverySnapshotTest.java
+++ b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/booking/BuildDeliverySnapshotTest.java
@@ -18,6 +18,7 @@
 package org.apache.zest.sample.dcicargo.sample_a.context.shipping.booking;
 
 import java.util.Date;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.unitofwork.UnitOfWork;
@@ -74,13 +75,15 @@ public class BuildDeliverySnapshotTest
     private TrackingId trackingId;
     private Cargo cargo;
     private Itinerary itinerary;
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void prepareTest()
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        uowf = module.unitOfWorkFactory();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         STOCKHOLM = uow.get( Location.class, SESTO.code().get() );
         SHANGHAI = uow.get( Location.class, CNSHA.code().get() );
@@ -153,7 +156,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_2c_ItineraryIsUnknown_buildFromRouteSpecification();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         RouteSpecification routeSpec = routeSpecification( HONGKONG, STOCKHOLM, day( 20 ) );
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
         Delivery delivery = new BuildDeliverySnapshot( routeSpec ).get();
@@ -268,7 +271,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_3a_CargoHasNoHandlingHistory();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         // Unexpected receipt in Shanghai
         HandlingEvent handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 1 ), day( 1 ), trackingId, HandlingEventType.RECEIVE, SHANGHAI, null );
@@ -294,7 +297,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4a_RECEIVE_1a_UnexpectedPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         // Expected receipt in Hong Kong
         HandlingEvent handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 1 ), day( 1 ), trackingId, HandlingEventType.RECEIVE, HONGKONG, null );
@@ -318,7 +321,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4a_RECEIVE_1b_ExpectedPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         // Unexpected load in Tokyo
         HandlingEvent handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 1 ), day( 1 ), trackingId, LOAD, TOKYO, V100S );
@@ -340,7 +343,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4b_LOAD_2a_UnexpectedPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         // Expected load in Hong Kong
         HandlingEvent handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 1 ), day( 1 ), trackingId, LOAD, HONGKONG, V100S );
@@ -364,7 +367,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4b_LOAD_2b_ExpectedPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         // Load onto unexpected voyage
         HandlingEvent handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 1 ), day( 1 ), trackingId, LOAD, HONGKONG, V400S );
@@ -386,7 +389,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4b_LOAD_2c_UnexpectedVoyageNotFromItinerary();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // The system doesn't currently check if handling events happen in the right order, so
@@ -415,7 +418,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4b_LOAD_2c_ExpectedButLaterVoyageInItinerary();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // Unexpected unload in Tokyo
@@ -508,7 +511,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4c_UNLOAD_1a_UnexpectedPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // Unload at midpoint location of itinerary
@@ -534,7 +537,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4c_UNLOAD_1b_ExpectedMidpointLocation();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // Unload at destination
@@ -563,7 +566,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4c_UNLOAD_1c_Destination();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // Cargo was handled by the customs authorities
@@ -590,7 +593,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4d_CUSTOMS_1a_CargoIsInDestinationPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // Cargo was claimed but not at destination location
@@ -616,7 +619,7 @@ public class BuildDeliverySnapshotTest
     {
         deviation_4e_CLAIM_1a_CargoIsNotInDestinationPort();
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
 
         // Cargo was claimed by customer at destination location

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/InspectCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/InspectCargoTest.java b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/InspectCargoTest.java
index e5f9ad6..6a434f9 100644
--- a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/InspectCargoTest.java
+++ b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/InspectCargoTest.java
@@ -17,6 +17,7 @@
  */
 package org.apache.zest.sample.dcicargo.sample_a.context.shipping.handling;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.unitofwork.UnitOfWork;
@@ -55,12 +56,14 @@ public class InspectCargoTest
     private Voyage V200T;
     private Voyage V300A;
     private HandlingEvent handlingEvent;
+    private UnitOfWorkFactory uowf;
 
     @Before
     public void beforeEachTest()
         throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        uowf = module.unitOfWorkFactory();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Cargos CARGOS = uow.get( Cargos.class, CargosEntity.CARGOS_ID );
         Location HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         SHANGHAI = uow.get( Location.class, CNSHA.code().get() );
@@ -89,7 +92,7 @@ public class InspectCargoTest
         throws Exception
     {
         // Create misdirected handling event for cargo (receipt in Shanghai is unexpected)
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 0 ), day( 0 ), trackingId, HandlingEventType.RECEIVE, SHANGHAI, null );
         Delivery delivery = new BuildDeliverySnapshot( cargo, handlingEvent ).get();
@@ -106,7 +109,7 @@ public class InspectCargoTest
     public void deviation_3b_CargoHasArrived()
         throws Exception
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 15 ), day( 15 ), trackingId, HandlingEventType.UNLOAD, STOCKHOLM, V300A );
         Delivery delivery = new BuildDeliverySnapshot( cargo, handlingEvent ).get();
@@ -124,7 +127,7 @@ public class InspectCargoTest
         throws Exception
     {
         logger.info( "  Handling cargo 'ABC' (unloaded in Dallas):" );
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HandlingEventsEntity HANDLING_EVENTS = uow.get( HandlingEventsEntity.class, HandlingEventsEntity.HANDLING_EVENTS_ID );
         handlingEvent = HANDLING_EVENTS.createHandlingEvent( day( 12 ), day( 12 ), trackingId, HandlingEventType.UNLOAD, DALLAS, V200T );
         cargo.delivery().set( new BuildDeliverySnapshot( cargo, handlingEvent ).get() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/RegisterHandlingEventTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/RegisterHandlingEventTest.java b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/RegisterHandlingEventTest.java
index 060d8d3..81e3ae6 100644
--- a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/RegisterHandlingEventTest.java
+++ b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/context/shipping/handling/RegisterHandlingEventTest.java
@@ -64,7 +64,7 @@ public class RegisterHandlingEventTest
 
     @Before
     public void beforeEachTest() throws Exception {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = module.unitOfWorkFactory().currentUnitOfWork();
         CARGOS = uow.get(Cargos.class,  CargosEntity.CARGOS_ID );
         HONGKONG = uow.get( Location.class, CNHKG.code().get() );
         STOCKHOLM = uow.get( Location.class, SESTO.code().get() );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseData.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseData.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseData.java
index a694e43..939a3d2 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseData.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseData.java
@@ -21,8 +21,8 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.List;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.sample.dcicargo.sample_b.context.interaction.handling.parsing.dto.ParsedHandlingEventData;
 import org.apache.zest.sample.dcicargo.sample_b.data.structure.delivery.Delivery;
 import org.apache.zest.sample.dcicargo.sample_b.data.structure.delivery.NextHandlingEvent;
@@ -57,23 +57,23 @@ public abstract class BaseData
     protected UnLocode USCHI;
     protected UnLocode USDAL;
     protected UnLocode USNYC;
-    protected final Module module;
+    protected ValueBuilderFactory vbf;
 
-    protected BaseData( Module module )
+    protected BaseData( ValueBuilderFactory vbf )
     {
-        this.module = module;
+        this.vbf = vbf;
     }
 
     protected UnLocode unlocode( String unlocodeString )
     {
-        ValueBuilder<UnLocode> unlocode = module.newValueBuilder( UnLocode.class );
+        ValueBuilder<UnLocode> unlocode = vbf.newValueBuilder( UnLocode.class );
         unlocode.prototype().code().set( unlocodeString );
         return unlocode.newInstance();
     }
 
     protected CarrierMovement carrierMovement( Location depLoc, Location arrLoc, Date depTime, Date arrTime )
     {
-        ValueBuilder<CarrierMovement> carrierMovement = module.newValueBuilder( CarrierMovement.class );
+        ValueBuilder<CarrierMovement> carrierMovement = vbf.newValueBuilder( CarrierMovement.class );
         carrierMovement.prototype().departureLocation().set( depLoc );
         carrierMovement.prototype().arrivalLocation().set( arrLoc );
         carrierMovement.prototype().departureTime().set( depTime );
@@ -83,7 +83,7 @@ public abstract class BaseData
 
     protected Schedule schedule( CarrierMovement... carrierMovements )
     {
-        ValueBuilder<Schedule> schedule = module.newValueBuilder( Schedule.class );
+        ValueBuilder<Schedule> schedule = vbf.newValueBuilder( Schedule.class );
         List<CarrierMovement> cm = new ArrayList<>();
         cm.addAll( Arrays.asList( carrierMovements ) );
         schedule.prototype().carrierMovements().set( cm );
@@ -92,7 +92,7 @@ public abstract class BaseData
 
     protected Leg leg( Voyage voyage, Location load, Location unload, Date loadTime, Date unloadTime )
     {
-        ValueBuilder<Leg> leg = module.newValueBuilder( Leg.class );
+        ValueBuilder<Leg> leg = vbf.newValueBuilder( Leg.class );
         leg.prototype().voyage().set( voyage );
         leg.prototype().loadLocation().set( load );
         leg.prototype().unloadLocation().set( unload );
@@ -103,7 +103,7 @@ public abstract class BaseData
 
     protected Itinerary itinerary( Leg... legArray )
     {
-        ValueBuilder<Itinerary> itinerary = module.newValueBuilder( Itinerary.class );
+        ValueBuilder<Itinerary> itinerary = vbf.newValueBuilder( Itinerary.class );
         List<Leg> legs = new ArrayList<>();
         legs.addAll( Arrays.asList( legArray ) );
         itinerary.prototype().legs().set( legs );
@@ -121,7 +121,7 @@ public abstract class BaseData
         NextHandlingEvent nextHandlingEvent
     )
     {
-        ValueBuilder<Delivery> delivery = module.newValueBuilder( Delivery.class );
+        ValueBuilder<Delivery> delivery = vbf.newValueBuilder( Delivery.class );
         delivery.prototype().timestamp().set( new Date() );
         delivery.prototype().lastHandlingEvent().set( lastHandlingEvent );
         delivery.prototype().transportStatus().set( transportStatus );
@@ -141,7 +141,7 @@ public abstract class BaseData
                                  Integer itineraryProgressIndex
     )
     {
-        ValueBuilder<Delivery> delivery = module.newValueBuilder( Delivery.class );
+        ValueBuilder<Delivery> delivery = vbf.newValueBuilder( Delivery.class );
         delivery.prototype().timestamp().set( date );
         delivery.prototype().transportStatus().set( transportStatus );
         delivery.prototype().routingStatus().set( routingStatus );
@@ -155,7 +155,7 @@ public abstract class BaseData
                                                    Voyage voyage
     )
     {
-        ValueBuilder<NextHandlingEvent> nextHandlingEvent = module.newValueBuilder( NextHandlingEvent.class );
+        ValueBuilder<NextHandlingEvent> nextHandlingEvent = vbf.newValueBuilder( NextHandlingEvent.class );
         nextHandlingEvent.prototype().handlingEventType().set( handlingEventType );
         nextHandlingEvent.prototype().location().set( location );
         nextHandlingEvent.prototype().time().set( time );
@@ -172,7 +172,7 @@ public abstract class BaseData
     )
         throws Exception
     {
-        ValueBuilder<ParsedHandlingEventData> attempt = module.newValueBuilder( ParsedHandlingEventData.class );
+        ValueBuilder<ParsedHandlingEventData> attempt = vbf.newValueBuilder( ParsedHandlingEventData.class );
         attempt.prototype().registrationTime().set( registrationTime );
         attempt.prototype().completionTime().set( completionTime );
         attempt.prototype().trackingIdString().set( trackingIdString );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseDataService.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseDataService.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseDataService.java
index fd3a23e..c8ed3d2 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseDataService.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/BaseDataService.java
@@ -28,10 +28,11 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceComposite;
 import org.apache.zest.api.service.ServiceReference;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.sample.dcicargo.pathfinder_b.api.GraphTraversalService;
 import org.apache.zest.sample.dcicargo.pathfinder_b.api.TransitEdge;
 import org.apache.zest.sample.dcicargo.pathfinder_b.api.TransitPath;
@@ -51,8 +52,8 @@ import static org.apache.zest.api.usecase.UsecaseBuilder.newUsecase;
 /**
  * Create basic sample data on startup of application.
  */
-@Mixins(BaseDataService.Mixin.class)
-@Activators(BaseDataService.Activator.class)
+@Mixins( BaseDataService.Mixin.class )
+@Activators( BaseDataService.Activator.class )
 public interface BaseDataService
     extends ServiceComposite
 {
@@ -76,14 +77,17 @@ public interface BaseDataService
         extends BaseData
         implements BaseDataService
     {
+        @Structure
+        UnitOfWorkFactory uowf;
+
         @Service
         GraphTraversalService graphTraversalService;
 
         private static final Logger logger = LoggerFactory.getLogger( BaseDataService.class );
 
-        protected Mixin( @Structure Module module )
+        protected Mixin( @Structure ValueBuilderFactory vbf )
         {
-            super( module );
+            super( vbf );
         }
 
         @Override
@@ -92,7 +96,7 @@ public interface BaseDataService
         {
             logger.debug( "CREATING BASIC DATA..." );
 
-            UnitOfWork uow = module.newUnitOfWork( newUsecase( "Create base data" ) );
+            UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Create base data" ) );
 
             // Create locations
             location( unlocode( "AUMEL" ), "Melbourne" );
@@ -125,7 +129,7 @@ public interface BaseDataService
                         carrierMovements.add( carrierMovement( from, to, voyageEdge.getFromDate(), voyageEdge.getToDate() ) );
                     }
 
-                    ValueBuilder<Schedule> schedule = module.newValueBuilder( Schedule.class );
+                    ValueBuilder<Schedule> schedule = vbf.newValueBuilder( Schedule.class );
                     schedule.prototype().carrierMovements().set( carrierMovements );
                     voyage( voyageNumber, schedule.newInstance() );
                 }
@@ -154,14 +158,14 @@ public interface BaseDataService
 
         protected UnLocode unlocode( String unlocodeString )
         {
-            ValueBuilder<UnLocode> unlocode = module.newValueBuilder( UnLocode.class );
+            ValueBuilder<UnLocode> unlocode = vbf.newValueBuilder( UnLocode.class );
             unlocode.prototype().code().set( unlocodeString );
             return unlocode.newInstance();
         }
 
         protected Location location( UnLocode unlocode, String locationStr )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             EntityBuilder<Location> location = uow.newEntityBuilder( Location.class, unlocode.code().get() );
             location.instance().unLocode().set( unlocode );
             location.instance().name().set( locationStr );
@@ -170,11 +174,11 @@ public interface BaseDataService
 
         protected Voyage voyage( String voyageNumberStr, Schedule schedule )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             EntityBuilder<Voyage> voyage = uow.newEntityBuilder( Voyage.class, voyageNumberStr );
 
             // VoyageNumber
-            ValueBuilder<VoyageNumber> voyageNumber = module.newValueBuilder( VoyageNumber.class );
+            ValueBuilder<VoyageNumber> voyageNumber = vbf.newValueBuilder( VoyageNumber.class );
             voyageNumber.prototype().number().set( voyageNumberStr );
             voyage.instance().voyageNumber().set( voyageNumber.newInstance() );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/SampleDataService.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/SampleDataService.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/SampleDataService.java
index 5753a0c..b4866c1 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/SampleDataService.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/sampledata/SampleDataService.java
@@ -22,23 +22,23 @@ import java.util.Date;
 import java.util.List;
 import java.util.Random;
 import java.util.UUID;
-import org.joda.time.DateTime;
-import org.joda.time.LocalDate;
-import org.joda.time.LocalTime;
 import org.apache.zest.api.activation.ActivatorAdapter;
 import org.apache.zest.api.activation.Activators;
+import org.apache.zest.api.composite.TransientBuilderFactory;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.query.Query;
 import org.apache.zest.api.query.QueryBuilder;
+import org.apache.zest.api.query.QueryBuilderFactory;
 import org.apache.zest.api.service.ServiceComposite;
 import org.apache.zest.api.service.ServiceReference;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.Usecase;
 import org.apache.zest.api.usecase.UsecaseBuilder;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.sample.dcicargo.sample_b.context.interaction.booking.BookNewCargo;
 import org.apache.zest.sample.dcicargo.sample_b.context.interaction.booking.routing.AssignCargoToRoute;
 import org.apache.zest.sample.dcicargo.sample_b.context.interaction.handling.ProcessHandlingEvent;
@@ -55,6 +55,9 @@ import org.apache.zest.sample.dcicargo.sample_b.data.structure.itinerary.Itinera
 import org.apache.zest.sample.dcicargo.sample_b.data.structure.location.Location;
 import org.apache.zest.sample.dcicargo.sample_b.data.structure.voyage.CarrierMovement;
 import org.apache.zest.sample.dcicargo.sample_b.data.structure.voyage.Voyage;
+import org.joda.time.DateTime;
+import org.joda.time.LocalDate;
+import org.joda.time.LocalTime;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -71,8 +74,8 @@ import static org.apache.zest.sample.dcicargo.sample_b.infrastructure.dci.Contex
  *
  * Add more cases if needed in the loop below.
  */
-@Mixins(SampleDataService.Mixin.class)
-@Activators(SampleDataService.Activator.class)
+@Mixins( SampleDataService.Mixin.class )
+@Activators( SampleDataService.Activator.class )
 public interface SampleDataService
     extends ServiceComposite
 {
@@ -91,11 +94,20 @@ public interface SampleDataService
         }
     }
 
-    public abstract class Mixin
+    abstract class Mixin
         implements SampleDataService
     {
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
+
+        @Structure
+        ValueBuilderFactory vbf;
+
+        @Structure
+        QueryBuilderFactory qbf;
+
+        @Structure
+        TransientBuilderFactory tbf;
 
         @Service
         RoutingService routingService;
@@ -112,7 +124,7 @@ public interface SampleDataService
         public void insertSampleData()
             throws Exception
         {
-            prepareContextBaseClass( module );
+            prepareContextBaseClass( uowf, vbf );
 
             logger.info( "######  CREATING SAMPLE DATA...  ##########################################" );
 
@@ -120,11 +132,11 @@ public interface SampleDataService
             populateRandomCargos( 12 );
 
             // Handle cargos
-            UnitOfWork uow = module.newUnitOfWork( newUsecase( "Create sample data" ) );
+            UnitOfWork uow = uowf.newUnitOfWork( newUsecase( "Create sample data" ) );
             try
             {
                 int i = 11; // starting at 11 for sortable tracking id prefix in lists
-                QueryBuilder<Cargo> qb = module.newQueryBuilder( Cargo.class );
+                QueryBuilder<Cargo> qb = qbf.newQueryBuilder( Cargo.class );
                 for( Cargo cargo : uow.newQuery( qb ) )
 
                 {
@@ -157,7 +169,7 @@ public interface SampleDataService
                         Location origin = routeSpec.origin().get();
                         Location dest = routeSpec.destination().get();
                         Location badDest = null;
-                        Query<Location> locations = uow.newQuery( module.newQueryBuilder( Location.class ) );
+                        Query<Location> locations = uow.newQuery( qbf.newQueryBuilder( Location.class ) );
                         for( Location loc : locations )
                         {
                             if( !origin.equals( loc ) && !dest.equals( loc ) )
@@ -193,8 +205,8 @@ public interface SampleDataService
                         voyageNumber = nextEvent.voyage().get().voyageNumber().get().number().get();
 
                         // Find earliest wrong carrier movement (voyage) with same departure location
-                        final Query<Voyage> voyages = module.currentUnitOfWork()
-                            .newQuery( module.newQueryBuilder( Voyage.class ) );
+                        final Query<Voyage> voyages = uowf.currentUnitOfWork()
+                            .newQuery( qbf.newQueryBuilder( Voyage.class ) );
                         int depth = 0;
                         do
                         {
@@ -341,11 +353,11 @@ public interface SampleDataService
         private void populateRandomCargos( int numberOfCargos )
         {
             Usecase usecase = UsecaseBuilder.newUsecase( "Populate Random Cargos" );
-            UnitOfWork uow = module.newUnitOfWork( usecase );
+            UnitOfWork uow = uowf.newUnitOfWork( usecase );
 
             CargoAggregateRoot cargos = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 
-            Query<Location> allLocations = uow.newQuery( module.newQueryBuilder( Location.class ) );
+            Query<Location> allLocations = uow.newQuery( qbf.newQueryBuilder( Location.class ) );
             int locationSize = (int) allLocations.count();
 
             // Make array for selection of location with random index
@@ -402,7 +414,7 @@ public interface SampleDataService
         )
             throws Exception
         {
-            ValueBuilder<ParsedHandlingEventData> event = module.newValueBuilder( ParsedHandlingEventData.class );
+            ValueBuilder<ParsedHandlingEventData> event = vbf.newValueBuilder( ParsedHandlingEventData.class );
             event.prototype().registrationTime().set( registrationTime );
             event.prototype().completionTime().set( completionTime );
             event.prototype().trackingIdString().set( trackingIdString );
@@ -410,7 +422,7 @@ public interface SampleDataService
             event.prototype().unLocodeString().set( unLocodeString );
             event.prototype().voyageNumberString().set( voyageNumberString );
 
-            module.newTransient( ProcessHandlingEvent.class ).register( event.newInstance() );
+            tbf.newTransient( ProcessHandlingEvent.class ).register( event.newInstance() );
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/WicketZestApplication.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/WicketZestApplication.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/WicketZestApplication.java
index 55ceeab..ad391db 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/WicketZestApplication.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/WicketZestApplication.java
@@ -23,13 +23,17 @@ import org.apache.wicket.protocol.http.WebApplication;
 import org.apache.wicket.request.cycle.AbstractRequestCycleListener;
 import org.apache.wicket.request.cycle.RequestCycle;
 import org.apache.zest.api.ZestAPI;
+import org.apache.zest.api.composite.TransientBuilderFactory;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
+import org.apache.zest.api.query.QueryBuilderFactory;
 import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.UsecaseBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.bootstrap.ApplicationAssembler;
 import org.apache.zest.bootstrap.Energy4Java;
 import org.apache.zest.sample.dcicargo.sample_b.infrastructure.conversion.EntityToDTOService;
@@ -54,7 +58,16 @@ public class WicketZestApplication
     protected Module zestModule;
 
     @Structure
-    protected Module module;
+    protected UnitOfWorkFactory uowf;
+
+    @Structure
+    protected ValueBuilderFactory vbf;
+
+    @Structure
+    protected TransientBuilderFactory tbf;
+
+    @Structure
+    protected QueryBuilderFactory qbf;
 
     @Structure
     protected ZestAPI api;
@@ -118,10 +131,10 @@ public class WicketZestApplication
         startZest();
         handleUnitOfWork();
 
-        Context.prepareContextBaseClass( module );
-        BaseWebPage.prepareBaseWebPageClass( module );
+        Context.prepareContextBaseClass( uowf, vbf );
+        BaseWebPage.prepareBaseWebPageClass( tbf );
         ReadOnlyModel.prepareModelBaseClass( zestModule, api, valueConverter );
-        Queries.prepareQueriesBaseClass( module, module );
+        Queries.prepareQueriesBaseClass( uowf, qbf );
 
         wicketInit();
     }
@@ -163,14 +176,14 @@ public class WicketZestApplication
                 logger.debug( requestCycle.getRequest().toString() );
                 logger.debug( requestCycle.getRequest().getRequestParameters().toString() );
 
-                UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "REQUEST" ) );
+                UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "REQUEST" ) );
                 logger.debug( "  ### NEW " + uow + "   ### MODULE: " + zestModule );
             }
 
             @Override
             public void onEndRequest( final RequestCycle requestCycle )
             {
-                UnitOfWork uow = module.currentUnitOfWork();
+                UnitOfWork uow = uowf.currentUnitOfWork();
                 if( uow != null )
                 {
                     try

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/dci/Context.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/dci/Context.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/dci/Context.java
index f74c29b..f57a0be 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/dci/Context.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/dci/Context.java
@@ -19,8 +19,9 @@ package org.apache.zest.sample.dcicargo.sample_b.infrastructure.dci;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.api.value.ValueComposite;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -41,7 +42,8 @@ public abstract class Context
      *
      * All entities should be created through aggregate r
      */
-    private static Module module;
+    private static ValueBuilderFactory vbf;
+    private static UnitOfWorkFactory uowf;
 
     protected Context()
     {
@@ -122,22 +124,23 @@ public abstract class Context
 
     protected <T, U> T rolePlayer( Class<T> roleClass, Class<U> dataClass, String entityId )
     {
-        U dataObject = module.currentUnitOfWork().get( dataClass, entityId );
+        U dataObject = uowf.currentUnitOfWork().get( dataClass, entityId );
         return rolePlayer( roleClass, dataObject );
     }
 
     protected static <T> T loadEntity( Class<T> entityRoleClass, String entityId )
     {
-        return module.currentUnitOfWork().get( entityRoleClass, entityId );
+        return uowf.currentUnitOfWork().get( entityRoleClass, entityId );
     }
 
     protected static <T extends ValueComposite> ValueBuilder<T> valueBuilder( Class<T> valueClass )
     {
-        return module.newValueBuilder( valueClass );
+        return vbf.newValueBuilder( valueClass );
     }
 
-    public static void prepareContextBaseClass( Module module )
+    public static void prepareContextBaseClass( UnitOfWorkFactory uowf, ValueBuilderFactory vbf )
     {
-        Context.module = module;
+        Context.uowf = uowf;
+        Context.vbf = vbf;
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/EntityModel.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/EntityModel.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/EntityModel.java
index 459488b..4383ed1 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/EntityModel.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/EntityModel.java
@@ -73,10 +73,10 @@ public class EntityModel<T extends DTO, U extends EntityComposite>
 
     private U loadEntity()
     {
-        U entity = module.currentUnitOfWork().get( entityClass, identity );
+        U entity = uowf.currentUnitOfWork().get( entityClass, identity );
         if( entity == null )
         {
-            Usecase usecase = module.currentUnitOfWork().usecase();
+            Usecase usecase = uowf.currentUnitOfWork().usecase();
             throw new NoSuchEntityException( EntityReference.parseEntityReference( identity ), entityClass, usecase );
         }
         return entity;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/JSONModel.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/JSONModel.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/JSONModel.java
index aa9a2d9..4aa7567 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/JSONModel.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/JSONModel.java
@@ -35,7 +35,7 @@ public class JSONModel<T, U extends ValueComposite>
     @SuppressWarnings( "unchecked" )
     public JSONModel( T valueComposite, Class<U> valueCompositeClass )
     {
-        json = module.findService( ValueSerializer.class ).get().serialize( (U) valueComposite );;
+        json = serviceFinder.findService( ValueSerializer.class ).get().serialize( (U) valueComposite );;
         this.valueCompositeClass = valueCompositeClass;
     }
 
@@ -59,7 +59,7 @@ public class JSONModel<T, U extends ValueComposite>
         if( valueComposite == null && json != null )
         {
             // De-serialize
-            valueComposite = (T) module.newValueFromSerializedState( valueCompositeClass, json ); // Unchecked cast
+            valueComposite = (T) vbf.newValueFromSerializedState( valueCompositeClass, json ); // Unchecked cast
         }
         return valueComposite;
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/ReadOnlyModel.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/ReadOnlyModel.java b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/ReadOnlyModel.java
index fb99ade..ad3ef43 100644
--- a/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/ReadOnlyModel.java
+++ b/samples/dci-cargo/dcisample_b/src/main/java/org/apache/zest/sample/dcicargo/sample_b/infrastructure/model/ReadOnlyModel.java
@@ -19,7 +19,10 @@ package org.apache.zest.sample.dcicargo.sample_b.infrastructure.model;
 
 import org.apache.wicket.model.IModel;
 import org.apache.zest.api.ZestAPI;
+import org.apache.zest.api.service.ServiceFinder;
 import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.sample.dcicargo.sample_b.infrastructure.conversion.EntityToDTOService;
 
 /**
@@ -34,7 +37,9 @@ public abstract class ReadOnlyModel<T>
 
     static protected EntityToDTOService valueConverter;
     static protected ZestAPI api;
-    static protected Module module;
+    static protected ServiceFinder serviceFinder;
+    static protected UnitOfWorkFactory uowf;
+    static protected ValueBuilderFactory vbf;
 
     /**
      * This default implementation of setObject unconditionally throws an
@@ -64,7 +69,9 @@ public abstract class ReadOnlyModel<T>
                                               EntityToDTOService entityToDTO
     )
     {
-        module = m;
+        uowf = m.unitOfWorkFactory();
+        serviceFinder = m;
+        vbf = m;
         ReadOnlyModel.api = api;
         valueConverter = entityToDTO;
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestApplication.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestApplication.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestApplication.java
index fa2c3ed..1c51598 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestApplication.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestApplication.java
@@ -19,6 +19,9 @@ package org.apache.zest.sample.dcicargo.sample_b.bootstrap.test;
 
 import java.text.SimpleDateFormat;
 import java.util.Date;
+import org.apache.zest.api.query.QueryBuilderFactory;
+import org.apache.zest.api.service.ServiceFinder;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
@@ -65,6 +68,10 @@ import static org.junit.Assert.*;
 public class TestApplication
       extends BaseData
 {
+    protected static ServiceFinder serviceFinder;
+    protected static UnitOfWorkFactory uowf;
+    protected static QueryBuilderFactory qbf;
+
     // Logger for sub classes
     protected Logger logger = LoggerFactory.getLogger( getClass() );
 
@@ -157,7 +164,11 @@ public class TestApplication
         System.out.println( "\n@@@@@@@@@@@  TEST SUITE  @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" );
         app = new Energy4Java().newApplication( new TestAssembler() );
         app.activate();
-        Context.prepareContextBaseClass( findHostingModule() );
+        Module module = findHostingModule();
+        serviceFinder = module;
+        qbf = module;
+        uowf = module.unitOfWorkFactory();
+        Context.prepareContextBaseClass( module.unitOfWorkFactory(), module );
 
     }
 
@@ -175,11 +186,11 @@ public class TestApplication
     {
         logger.info( name.getMethodName() );
         Usecase usecase = UsecaseBuilder.newUsecase( "Usecase:" + name );
-        UnitOfWork uow = module.newUnitOfWork(usecase);
+        UnitOfWork uow = uowf.newUnitOfWork( usecase);
         populateTestData();
 
         ServiceReference<RouteSpecificationFactoryService> routeSpecFactoryServiceRef =
-            module.findService( RouteSpecificationFactoryService.class );
+            serviceFinder.findService( RouteSpecificationFactoryService.class );
         routeSpecFactory = routeSpecFactoryServiceRef.get();
 
         // Separate test suites in console output
@@ -189,16 +200,16 @@ public class TestApplication
     @After
     public void concludeTests()
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         if (uow != null)
         {
             uow.discard();
         }
-        if( module.isUnitOfWorkActive() )
+        if( uowf.isUnitOfWorkActive() )
         {
-            while( module.isUnitOfWorkActive() )
+            while( uowf.isUnitOfWorkActive() )
             {
-                uow = module.currentUnitOfWork();
+                uow = uowf.currentUnitOfWork();
                 if( uow.isOpen() )
                 {
                     System.err.println( "UnitOfWork not cleaned up:" + uow.usecase().name() );
@@ -247,7 +258,7 @@ public class TestApplication
         USDAL = unlocode( "USDAL" ); // Dallas
         USNYC = unlocode( "USNYC" ); // New York
 
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
 
         // Get locations created in BaseDataService on startup
         MELBOURNE = uow.get( Location.class, "AUMEL" );
@@ -430,11 +441,11 @@ public class TestApplication
 
     protected Voyage voyage( String voyageNumberStr, Schedule schedule )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<Voyage> voyage = uow.newEntityBuilder( Voyage.class, voyageNumberStr );
 
         // VoyageNumber
-        ValueBuilder<VoyageNumber> voyageNumber = module.newValueBuilder( VoyageNumber.class );
+        ValueBuilder<VoyageNumber> voyageNumber = vbf.newValueBuilder( VoyageNumber.class );
         voyageNumber.prototype().number().set( voyageNumberStr );
         voyage.instance().voyageNumber().set( voyageNumber.newInstance() );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestAssembler.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestAssembler.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestAssembler.java
index 1995a0b..42e7a04 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestAssembler.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/bootstrap/test/TestAssembler.java
@@ -113,7 +113,7 @@ public class TestAssembler
     private void assembleBootstrapLayer( LayerAssembly bootstrapLayer )
         throws AssemblyException
     {
-        ModuleAssembly bootstrapModule = bootstrapLayer.module( "BOOTSTRAP-Bootstrap" );
+        ModuleAssembly bootstrapModule = bootstrapLayer.module( "BOOTSTRAP-Bootstrap" ).withDefaultUnitOfWorkFactory();
 
         // Load base data on startup
         bootstrapModule
@@ -125,7 +125,7 @@ public class TestAssembler
     private void assembleContextLayer( LayerAssembly contextLayer )
         throws AssemblyException
     {
-        ModuleAssembly roleMapModule = contextLayer.module( "CONTEXT-RoleMap" );
+        ModuleAssembly roleMapModule = contextLayer.module( "CONTEXT-RoleMap" ).withDefaultUnitOfWorkFactory();
 
         // Role-playing entities
         roleMapModule
@@ -143,13 +143,13 @@ public class TestAssembler
                 VoyageEntity.class )
             .visibleIn( application );
 
-        ModuleAssembly interactionModule = contextLayer.module( "CONTEXT-Interaction" );
+        ModuleAssembly interactionModule = contextLayer.module( "CONTEXT-Interaction" ).withDefaultUnitOfWorkFactory();
         interactionModule
             .transients(
                 ProcessHandlingEvent.class )
             .visibleIn( application );
 
-        ModuleAssembly contextServiceModule = contextLayer.module( "CONTEXT-Service" );
+        ModuleAssembly contextServiceModule = contextLayer.module( "CONTEXT-Service" ).withDefaultUnitOfWorkFactory();
         contextServiceModule
             .services(
                 ParseHandlingEventData.class,
@@ -167,7 +167,7 @@ public class TestAssembler
         throws AssemblyException
     {
         // Non-role-playing values
-        ModuleAssembly structureModule = dataLayer.module( "DATA-Structure" );
+        ModuleAssembly structureModule = dataLayer.module( "DATA-Structure" ).withDefaultUnitOfWorkFactory();
         structureModule
             .values(
                 TrackingId.class,
@@ -187,14 +187,14 @@ public class TestAssembler
     private void assembleInfrastructureLayer( LayerAssembly infrastructureLayer )
         throws AssemblyException
     {
-        ModuleAssembly serializationModule = infrastructureLayer.module( "INFRASTRUCTURE-Serialization" );
+        ModuleAssembly serializationModule = infrastructureLayer.module( "INFRASTRUCTURE-Serialization" ).withDefaultUnitOfWorkFactory();
         serializationModule
             .services( OrgJsonValueSerializationService.class )
             .taggedWith( ValueSerialization.Formats.JSON )
             .setMetaInfo( (Function<Application, Module>) application -> application.findModule( "CONTEXT", "CONTEXT-RoleMap" ) )
         .visibleIn( application );
 
-        ModuleAssembly indexingModule = infrastructureLayer.module( "INFRASTRUCTURE-Indexing" );
+        ModuleAssembly indexingModule = infrastructureLayer.module( "INFRASTRUCTURE-Indexing" ).withDefaultUnitOfWorkFactory();
         indexingModule
             .objects(
                 EntityStateSerializer.class,
@@ -207,14 +207,14 @@ public class TestAssembler
             .visibleIn( application )
             .instantiateOnStartup();
 
-        ModuleAssembly entityStoreModule = infrastructureLayer.module( "INFRASTRUCTURE-EntityStore" );
+        ModuleAssembly entityStoreModule = infrastructureLayer.module( "INFRASTRUCTURE-EntityStore" ).withDefaultUnitOfWorkFactory();
         entityStoreModule
             .addServices(
                 MemoryEntityStoreService.class,
                 UuidIdentityGeneratorService.class )
             .visibleIn( application );
 
-        ModuleAssembly externalServiceModule = infrastructureLayer.module( "INFRASTRUCTURE-ExternalService" );
+        ModuleAssembly externalServiceModule = infrastructureLayer.module( "INFRASTRUCTURE-ExternalService" ).withDefaultUnitOfWorkFactory();
         externalServiceModule
             .importedServices(
                 GraphTraversalService.class )

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/BookNewCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/BookNewCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/BookNewCargoTest.java
index cacd426..aa9a944 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/BookNewCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/BookNewCargoTest.java
@@ -50,7 +50,7 @@ public class BookNewCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
     }
 
@@ -101,7 +101,7 @@ public class BookNewCargoTest extends TestApplication
         throws Exception
     {
         deviation_2b_DeadlineTomorrowIsOkay();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         trackingId = new BookNewCargo( CARGOS, HONGKONG, STOCKHOLM, DAY24 ).getTrackingId();
         cargo = uow.get( CargoEntity.class, trackingId.id().get() );
         assertThat( cargo.routeSpecification().get().origin().get(), is( equalTo( HONGKONG ) ) );
@@ -114,7 +114,7 @@ public class BookNewCargoTest extends TestApplication
         throws Exception
     {
         step_2_CanCreateRouteSpecification();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         trackingId = new BookNewCargo( CARGOS, HONGKONG, STOCKHOLM, DAY24 ).getTrackingId();
         cargo = uow.get( CargoEntity.class, trackingId.id().get() );
         assertDelivery( null, null, null, null,
@@ -137,7 +137,7 @@ public class BookNewCargoTest extends TestApplication
         throws Exception
     {
         deviation_4a_TrackingIdTooShort();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         trackingId = new BookNewCargo( CARGOS, HONGKONG, STOCKHOLM, DAY24 ).withTrackingId( "yes" );
         cargo = uow.get( CargoEntity.class, trackingId.id().get() );
         assertThat( cargo.trackingId().get().id().get(), is( equalTo( "yes" ) ) );
@@ -157,7 +157,7 @@ public class BookNewCargoTest extends TestApplication
         throws Exception
     {
         deviation_4a_TrackingIdTooLong();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         trackingId = new BookNewCargo( CARGOS, HONGKONG, STOCKHOLM, DAY24 ).withTrackingId( "123456789012345678901234567890" );
         cargo = uow.get( CargoEntity.class, trackingId.id().get() );
         assertThat( cargo.trackingId().get().id().get(), is( equalTo( "123456789012345678901234567890" ) ) );
@@ -202,7 +202,7 @@ public class BookNewCargoTest extends TestApplication
         throws Exception
     {
         step_4_CanAutoCreateTrackingIdFromNull();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         trackingId = new BookNewCargo( CARGOS, HONGKONG, STOCKHOLM, DAY24 ).withTrackingId( "ABC" );
         cargo = uow.get( CargoEntity.class, trackingId.id().get() );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/AssignCargoToRouteTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/AssignCargoToRouteTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/AssignCargoToRouteTest.java
index 7682ceb..f21169b 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/AssignCargoToRouteTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/AssignCargoToRouteTest.java
@@ -55,7 +55,7 @@ public class AssignCargoToRouteTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/RegisterNewDestinationTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/RegisterNewDestinationTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/RegisterNewDestinationTest.java
index 00474d2..c35d4e2 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/RegisterNewDestinationTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/routing/RegisterNewDestinationTest.java
@@ -54,7 +54,7 @@ public class RegisterNewDestinationTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/specification/DeriveUpdatedRouteSpecTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/specification/DeriveUpdatedRouteSpecTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/specification/DeriveUpdatedRouteSpecTest.java
index e8fb093..a8bb584 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/specification/DeriveUpdatedRouteSpecTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/booking/specification/DeriveUpdatedRouteSpecTest.java
@@ -42,7 +42,7 @@ public class DeriveUpdatedRouteSpecTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectArrivedCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectArrivedCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectArrivedCargoTest.java
index 1b61869..b1fb4c3 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectArrivedCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectArrivedCargoTest.java
@@ -48,7 +48,7 @@ public class InspectArrivedCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectCargoInCustomsTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectCargoInCustomsTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectCargoInCustomsTest.java
index 7b6bd59..7f32055 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectCargoInCustomsTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectCargoInCustomsTest.java
@@ -47,7 +47,7 @@ public class InspectCargoInCustomsTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectClaimedCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectClaimedCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectClaimedCargoTest.java
index bf8aa65..d161ef3 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectClaimedCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectClaimedCargoTest.java
@@ -45,7 +45,7 @@ public class InspectClaimedCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectLoadedCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectLoadedCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectLoadedCargoTest.java
index ddc6026..6d9b4f3 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectLoadedCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectLoadedCargoTest.java
@@ -63,7 +63,7 @@ public class InspectLoadedCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         // Create new cargo

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectReceivedCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectReceivedCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectReceivedCargoTest.java
index 89c45bf..c7591ae 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectReceivedCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectReceivedCargoTest.java
@@ -53,7 +53,7 @@ public class InspectReceivedCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnhandledCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnhandledCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnhandledCargoTest.java
index 4f6b473..a5d1242 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnhandledCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnhandledCargoTest.java
@@ -47,7 +47,7 @@ public class InspectUnhandledCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnloadedCargoTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnloadedCargoTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnloadedCargoTest.java
index a8b8a31..7146839 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnloadedCargoTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/inspection/event/InspectUnloadedCargoTest.java
@@ -55,7 +55,7 @@ public class InspectUnloadedCargoTest extends TestApplication
         throws Exception
     {
         super.prepareTest();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         HANDLING_EVENTS = uow.get( HandlingEventAggregateRoot.class, HandlingEventAggregateRoot.HANDLING_EVENTS_ID );
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/parsing/ParseHandlingEventDataTest.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/parsing/ParseHandlingEventDataTest.java b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/parsing/ParseHandlingEventDataTest.java
index d296149..1b81117 100644
--- a/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/parsing/ParseHandlingEventDataTest.java
+++ b/samples/dci-cargo/dcisample_b/src/test/java/org/apache/zest/sample/dcicargo/sample_b/context/test/handling/parsing/ParseHandlingEventDataTest.java
@@ -46,7 +46,7 @@ public class ParseHandlingEventDataTest extends TestApplication
     {
         super.prepareTest();
         TestApplication.setup();
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         CargoAggregateRoot CARGOS = uow.get( CargoAggregateRoot.class, CargoAggregateRoot.CARGOS_ID );
 
         // Create new cargo
@@ -60,7 +60,7 @@ public class ParseHandlingEventDataTest extends TestApplication
 
         // Start ParseHandlingEventData service
         ServiceReference<ParseHandlingEventData> ParseHandlingEventDataRef =
-            module.findService( ParseHandlingEventData.class );
+            serviceFinder.findService( ParseHandlingEventData.class );
         handlingEventParser = ParseHandlingEventDataRef.get();
     }
 


[9/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
ZEST-132, ZEST-97
   UnitOfWorkFactory as a customizable Service
   UnitOfWork as a customizable Transient
   Class can be a Transient directly, with itself as both the Composite Type and the Mixin.
   SideEffects declarations on methods.


Project: http://git-wip-us.apache.org/repos/asf/zest-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/zest-java/commit/a5be013f
Tree: http://git-wip-us.apache.org/repos/asf/zest-java/tree/a5be013f
Diff: http://git-wip-us.apache.org/repos/asf/zest-java/diff/a5be013f

Branch: refs/heads/ZEST-132
Commit: a5be013f39cba9642114e01486cdff0c355569f2
Parents: 6138c30
Author: Niclas Hedhman <ni...@hedhman.org>
Authored: Wed Dec 16 14:17:22 2015 +0800
Committer: Niclas Hedhman <ni...@hedhman.org>
Committed: Wed Dec 16 14:17:27 2015 +0800

----------------------------------------------------------------------
 .../zest/api/configuration/Configuration.java   |   7 +-
 .../zest/api/entity/EntityBuilderTemplate.java  |   2 +-
 .../org/apache/zest/api/structure/Module.java   |  15 +-
 .../java/org/apache/zest/api/type/HasTypes.java |   6 +
 .../org/apache/zest/api/type/ValueType.java     |   1 +
 .../apache/zest/api/unitofwork/UnitOfWork.java  |   7 +-
 .../zest/api/unitofwork/UnitOfWorkTemplate.java |   2 +-
 .../unitofwork/concern/UnitOfWorkConcern.java   |  20 +-
 .../java/org/apache/zest/api/OperatorsTest.java |   8 +-
 .../api/injection/scope/StateFieldTest.java     |   4 +-
 .../zest/api/property/PropertyErrorTest.java    |   2 +-
 .../apache/zest/api/unitofwork/RemovalTest.java |   4 +-
 .../zest/api/value/DocumentationSupport.java    |  67 +-
 .../zest/api/value/ValueCompositeTest.java      |   6 +-
 .../apache/zest/bootstrap/ModuleAssembly.java   |  36 +-
 .../unitofwork/DefaultUnitOfWorkAssembler.java  |  55 ++
 .../apache/zest/bootstrap/ClassScannerTest.java |   2 +
 .../apache/zest/runtime/ZestRuntimeImpl.java    |   2 +-
 .../association/ManyAssociationModel.java       |   5 +-
 .../association/ManyAssociationsModel.java      |   2 +-
 .../association/NamedAssociationModel.java      |   5 +-
 .../association/NamedAssociationsModel.java     |   2 +-
 .../bootstrap/CompositeAssemblyImpl.java        | 141 +++-
 .../runtime/bootstrap/ModuleAssemblyImpl.java   |  12 +-
 .../zest/runtime/composite/CompositeModel.java  |   5 +-
 .../composite/TransientBuilderInstance.java     |   2 +-
 .../runtime/composite/TransientClassLoader.java |   3 +-
 .../zest/runtime/entity/EntityInstance.java     |   5 +-
 .../apache/zest/runtime/entity/EntityModel.java |   2 +-
 .../runtime/entity/EntityStateInstance.java     |   9 +-
 .../runtime/injection/InjectedFieldsModel.java  |  23 +-
 .../StructureInjectionProviderFactory.java      |   2 +-
 .../zest/runtime/service/ServicesModel.java     |  12 +
 .../zest/runtime/structure/LayerInstance.java   |   3 +-
 .../zest/runtime/structure/ModuleInstance.java  | 136 +---
 .../runtime/structure/ModuleUnitOfWork.java     | 769 ------------------
 .../zest/runtime/structure/TypeLookup.java      | 526 -------------
 .../zest/runtime/structure/TypeLookupImpl.java  | 538 +++++++++++++
 .../runtime/structure/UsedLayersInstance.java   |   3 +-
 .../unitofwork/EntityBuilderInstance.java       |   3 +-
 .../zest/runtime/unitofwork/EntityFunction.java |  46 ++
 .../runtime/unitofwork/ModuleUnitOfWork.java    | 777 +++++++++++++++++++
 .../unitofwork/UnitOfWorkFactoryMixin.java      | 100 +++
 .../runtime/unitofwork/UnitOfWorkInstance.java  |  40 +-
 .../runtime/value/ValueBuilderInstance.java     |   2 +-
 .../value/ValueBuilderWithPrototype.java        |   2 +-
 .../runtime/value/ValueBuilderWithState.java    |   2 +-
 .../zest/runtime/value/ValueStateInstance.java  |  11 +-
 .../apache/zest/api/common/OptionalTest.java    |   6 +-
 .../zest/api/common/PropertyErrorTest.java      |   2 +-
 .../zest/api/common/PropertyTypeTest.java       |   2 +-
 .../org/apache/zest/api/common/RemovalTest.java |   4 +-
 .../zest/api/common/ValueCompositeTest.java     |   2 +-
 ...faceCollisionWithRelatedReturnTypesTest.java |  18 +-
 .../qi377/SetAssociationInSideEffectTest.java   |   2 +-
 .../apache/zest/regression/qi382/Qi382Test.java |  10 +-
 .../apache/zest/regression/qi383/Qi383Test.java |   2 +-
 .../apache/zest/regression/qi59/IssueTest.java  |   4 +-
 .../apache/zest/regression/qi94/IssueTest.java  |   2 +-
 .../org/apache/zest/runtime/ZestAPITest.java    |   2 +-
 .../org/apache/zest/runtime/ZestSPITest.java    |   4 +-
 .../AppliesToOrConditionQI241Test.java          |   6 +-
 .../association/AssociationAssignmentTest.java  |   4 +-
 .../association/AssociationEqualityTest.java    |  18 +-
 .../runtime/composite/TransientAsClassTest.java |  22 +-
 .../composite/TransientClassLoaderTest.java     |  30 +
 .../runtime/concerns/GenericConcernTest.java    |   2 +-
 .../zest/runtime/entity/AggregatedTest.java     |  10 +-
 .../entity/EntityBuilderWithStateTest.java      |  68 +-
 .../entity/EntityCompositeEqualityTest.java     |   2 +-
 .../zest/runtime/entity/EntityCreationTest.java |   4 +-
 .../zest/runtime/entity/EntityTypeTest.java     |   2 +-
 .../runtime/entity/EntityVisibilityTest.java    |  58 +-
 .../zest/runtime/entity/LifecycleTest.java      |   4 +-
 .../entity/associations/AssociationTest.java    |   2 +-
 .../associations/ImmutableAssociationTest.java  |   8 +-
 .../ConstructorInjectionOfThisTest.java         |   2 +
 .../injection/UnitOfWorkInjectionTest.java      |  10 +-
 .../TransientInstantiationTests.java            |   1 -
 .../zest/runtime/mixin/AssemblyMixinTest.java   |   4 +-
 .../zest/runtime/mixin/AssemblyRoleTest.java    |   6 +-
 .../runtime/objects/ObjectVisibilityTest.java   |  35 +-
 .../runtime/property/ImmutablePropertyTest.java |   2 +-
 .../runtime/query/IterableQuerySourceTest.java  |   6 +-
 .../zest/runtime/query/NonQueryableTest.java    |   4 +-
 .../runtime/service/AvailableServiceTest.java   |   4 +
 .../zest/runtime/service/ConfigurationTest.java |   6 +-
 .../runtime/service/ServiceVisibilityTest.java  |  33 +-
 .../structure/TypeToCompositeLookupTest.java    |  26 +-
 .../transients/TransientVisibilityTest.java     |  44 +-
 .../unitofwork/AutoCloseableUoWTest.java        |   6 +-
 .../unitofwork/PrivateEntityUnitOfWorkTest.java |  51 +-
 .../zest/runtime/unitofwork/RemovalTest.java    |  20 +-
 .../unitofwork/UnitOfWorkFactoryTest.java       |   2 +-
 .../zest/runtime/value/ValueComposite2Test.java |   2 +
 .../ValueInjectionDeserializationTest.java      |   4 +-
 .../zest/runtime/value/ValueVisibilityTest.java |  35 +-
 .../runtime/value/ValueWithAssociationTest.java |  12 +-
 .../visibility/VisibilityInUnitOfWorkTest.java  |  55 +-
 .../helpers/JSONMapEntityStoreMixin.java        |   2 +-
 .../helpers/MapEntityStoreMixin.java            |   2 +-
 .../org/apache/zest/spi/module/ModelModule.java | 107 ---
 .../org/apache/zest/spi/module/ModuleSpi.java   |   7 +
 .../apache/zest/spi/structure/ModelModule.java  | 107 +++
 .../apache/zest/spi/structure/TypeLookup.java   | 125 +++
 .../zest/test/AbstractZestScenarioTest.java     |  25 +-
 .../org/apache/zest/test/AbstractZestTest.java  |  13 +-
 .../zest/test/cache/AbstractCachePoolTest.java  |   1 -
 .../test/entity/AbstractEntityStoreTest.java    |  42 +-
 .../test/indexing/AbstractAnyQueryTest.java     |   2 +-
 .../org/apache/zest/test/indexing/TestData.java |  15 +-
 .../layered/assembly/AccountModule.java         |   1 +
 .../indexing/layered/assembly/ConfigModule.java |   1 +
 .../indexing/layered/assembly/FamilyModule.java |   1 +
 .../layered/assembly/PersistenceModule.java     |   1 +
 .../layered/assembly/TestExecutionModule.java   |   1 +
 .../layered/assembly/TestSuite1Module.java      |   1 +
 .../layered/assembly/TestSuite2Module.java      |   1 +
 .../layered/assembly/TestSuite3Module.java      |   1 +
 ...AbstractValueCompositeSerializationTest.java |   4 +-
 .../prefs/PreferencesEntityStoreMixin.java      |   2 +-
 .../entitystore/sql/SQLEntityStoreMixin.java    |   2 +-
 .../sql/DerbySQLEntityStoreTest.java            |   2 +-
 .../entitystore/sql/MySQLEntityStoreTest.java   |   2 +-
 .../sql/PostgreSQLEntityStoreTest.java          |   2 +-
 .../ElasticSearchQueryMultimoduleTest.java      |   2 +
 .../index/elasticsearch/ElasticSearchTest.java  |   4 +-
 .../index/elasticsearch/ImmenseTermTest.java    |   6 +-
 .../apache/zest/index/rdf/ContainsAllTest.java  |  12 +-
 .../org/apache/zest/index/rdf/ContainsTest.java |  12 +-
 .../apache/zest/index/rdf/MultiLayeredTest.java |   3 +-
 .../zest/index/rdf/RDFPerformanceTest.java      |  16 +-
 .../index/rdf/RdfNamedQueryMultimoduleTest.java |   3 +
 .../zest/index/rdf/RdfQueryMultimoduleTest.java |   4 +
 .../org/apache/zest/index/rdf/RdfQueryTest.java |   2 +
 .../zest/index/rdf/qi173/Qi173IssueTest.java    |   6 +-
 .../zest/index/rdf/qi64/AbstractIssueTest.java  |   2 +-
 .../withPropagationMandatory/IssueTest.java     |   8 +-
 .../qi64/withPropagationRequired/IssueTest.java |  10 +-
 .../withPropagationRequiresNew/IssueTest.java   |  10 +-
 .../zest/index/rdf/qi66/Qi66IssueTest.java      |   4 +-
 .../zest/index/rdf/qi95/Qi95IssueTest.java      |  13 +-
 .../zest/index/solr/SolrQueryServiceTest.java   |   4 +-
 .../support/skeletons/AbstractSQLQuerying.java  |   8 +-
 .../postgresql/PostgreSQLDBIntegrityTest.java   |  10 +-
 .../metrics/yammer/NoMetricsInstalledTest.java  |   4 +-
 .../apache/zest/metrics/yammer/YammerTest.java  |   4 +-
 .../apache/zest/migration/MigrationTest.java    |  10 +-
 .../zest/index/reindexer/ReindexerTest.java     |   4 +-
 .../zest/library/alarm/AlarmPointFactory.java   |  29 +-
 .../apache/zest/library/alarm/AlarmProxy.java   |  20 +-
 .../library/alarm/AlarmHistoryImplTest.java     |   6 +-
 .../zest/library/alarm/AlarmPointImplTest.java  |   6 +-
 .../zest/library/alarm/AlarmProxyTest.java      |   2 +-
 .../zest/library/alarm/AlarmServiceTest.java    |   6 +-
 .../library/alarm/ExtendedAlarmModelTest.java   |   8 +-
 .../library/alarm/SimpleAlarmModelTest.java     |   8 +-
 .../library/alarm/StandardAlarmModelTest.java   |   8 +-
 .../conversion/values/ValueToEntityMixin.java   |  22 +-
 .../conversion/values/EntityToValueTest.java    |  10 +-
 .../values/NestedValuesConversionTest.java      |   2 +-
 .../conversion/values/ValueToEntityTest.java    |  26 +-
 .../source/jdbm/JdbmEventStoreServiceTest.java  |   4 +-
 .../server/DomainEventSourceResourceSample.java |   2 +-
 .../application/ApplicationEventTest.java       |   6 +-
 .../eventsourcing/domain/DomainEventTest.java   |   2 +-
 .../source/helper/DomainEventTrackerTest.java   |   2 +-
 .../domain/source/helper/EventRouterTest.java   |   2 +
 .../domain/source/helper/EventsTest.java        |   2 +
 .../source/helper/UnitOfWorkRouterTest.java     |   2 +
 .../library/scala/HelloWorldCompositeTest.java  |   6 +-
 .../zest/library/logging/DebuggingTest.java     |   2 +-
 .../zest/library/logging/TracingTest.java       |   8 +-
 .../rdf/entity/EntitySerializerTest.java        |   2 +-
 .../rdf/entity/EntityTypeSerializerTest.java    |   2 +-
 .../ContextResourceClientFactoryTest.java       |  15 +-
 .../rest/client/ContinuousIntegrationTest.java  |   3 +-
 .../rest/server/api/ContextResource.java        |  24 +-
 .../library/rest/server/api/ContextRestlet.java |  21 +-
 .../requestreader/DefaultRequestReader.java     |  74 +-
 .../library/rest/admin/RestApplication.java     |  23 +-
 .../zest/library/rest/admin/RestTest.java       |  56 +-
 .../zest/library/scheduler/Scheduler.java       |   3 -
 .../library/scheduler/SchedulesHandler.java     |  19 +-
 .../defaults/DefaultScheduleFactoryMixin.java   |  16 +-
 .../library/scheduler/internal/Execution.java   |  14 +-
 .../scheduler/internal/SchedulerMixin.java      |   8 +-
 .../library/scheduler/internal/TaskRunner.java  |  12 +-
 .../library/scheduler/CronScheduleTest.java     |   2 +-
 .../zest/library/scheduler/SchedulerTest.java   |  14 +-
 .../domain/passwords/PasswordRealmMixin.java    |  67 +-
 .../library/shiro/domain/permissions/Role.java  |   6 +-
 .../shiro/domain/permissions/RoleFactory.java   |   6 +-
 .../zest/library/shiro/PasswordDomainTest.java  |   9 +-
 .../library/shiro/PermissionsDomainTest.java    |   9 +-
 .../sql/liquibase/LiquibaseServiceTest.java     |   3 +
 .../AbstractDataSourceServiceImporterMixin.java |  12 +-
 .../DataSourceConfigurationManagerService.java  |   7 +-
 ...taSourceConfigurationManagerServiceTest.java |   9 +-
 .../uowfile/internal/UoWFileFactory.java        |   5 +-
 .../zest/library/uowfile/HasUoWFileTest.java    |  30 +-
 .../zest/library/uowfile/HasUoWFilesTest.java   |  29 +-
 .../zest/manual/recipes/assemble/Docs.java      |   3 +-
 .../createEntity/CarEntityFactoryMixin.java     |  19 +-
 .../bootstrap/sampledata/BaseDataService.java   |   6 +-
 .../infrastructure/model/EntityModel.java       |   4 +-
 .../bootstrap/test/TestApplication.java         |  18 +-
 .../sample_a/bootstrap/test/TestAssembler.java  | 175 +++--
 .../shipping/booking/BookNewCargoTest.java      |  20 +-
 .../booking/BuildDeliverySnapshotTest.java      |  31 +-
 .../shipping/handling/InspectCargoTest.java     |  11 +-
 .../handling/RegisterHandlingEventTest.java     |   2 +-
 .../sample_b/bootstrap/sampledata/BaseData.java |  26 +-
 .../bootstrap/sampledata/BaseDataService.java   |  26 +-
 .../bootstrap/sampledata/SampleDataService.java |  48 +-
 .../infrastructure/WicketZestApplication.java   |  25 +-
 .../sample_b/infrastructure/dci/Context.java    |  17 +-
 .../infrastructure/model/EntityModel.java       |   4 +-
 .../infrastructure/model/JSONModel.java         |   4 +-
 .../infrastructure/model/ReadOnlyModel.java     |  11 +-
 .../bootstrap/test/TestApplication.java         |  31 +-
 .../sample_b/bootstrap/test/TestAssembler.java  |  18 +-
 .../context/test/booking/BookNewCargoTest.java  |  12 +-
 .../booking/routing/AssignCargoToRouteTest.java |   2 +-
 .../routing/RegisterNewDestinationTest.java     |   2 +-
 .../DeriveUpdatedRouteSpecTest.java             |   2 +-
 .../event/InspectArrivedCargoTest.java          |   2 +-
 .../event/InspectCargoInCustomsTest.java        |   2 +-
 .../event/InspectClaimedCargoTest.java          |   2 +-
 .../event/InspectLoadedCargoTest.java           |   2 +-
 .../event/InspectReceivedCargoTest.java         |   2 +-
 .../event/InspectUnhandledCargoTest.java        |   2 +-
 .../event/InspectUnloadedCargoTest.java         |   2 +-
 .../parsing/ParseHandlingEventDataTest.java     |   4 +-
 .../registration/RegisterHandlingEventTest.java |  18 +-
 .../moneytransfer/test/TransferMoneyTest.java   |  18 +-
 .../moneytransfer/test/TransferMoneyTest2.java  |  16 +-
 .../sample/forum/context/EventsService.java     |  15 +-
 .../administration/ForumAdministration.java     |  13 +-
 .../administration/ForumsAdministration.java    |   6 +-
 .../zest/sample/forum/context/login/Login.java  |  18 +-
 .../sample/forum/context/view/ViewBoard.java    |  10 +-
 .../sample/forum/context/view/ViewPost.java     |   8 +-
 .../zest/sample/forum/data/entity/Forums.java   |  12 +-
 .../zest/sample/forum/data/entity/Users.java    |  18 +-
 .../sample/forum/domainevent/DomainEvent.java   |  14 +-
 .../zest/sample/forum/rest/ForumRestlet.java    |   2 +-
 .../sample/forum/service/BootstrapData.java     |  16 +-
 .../org/apache/zest/sample/sqlsupport/Main.java |   8 +-
 .../AbstractEntityStorePerformanceTest.java     | 285 +++----
 .../sql/DerbySQLEntityStorePerformanceTest.java |   6 +-
 .../PostgreSQLEntityStorePerformanceTest.java   |   2 +-
 .../indexing/rdf/QueryPerformanceTest.java      |  29 +-
 .../tree/TreeModelCellRenderer.properties       |   2 +-
 .../zest/envisage/sample/EnvisageSample.java    |   6 +-
 .../zest/tools/model/VisitableDetailTest.java   |  24 +-
 .../apache/zest/tutorials/hello/HelloTest4.java |   4 +-
 .../demo/thirtyminutes/ThirtyMinutesDocs.java   |  19 +-
 258 files changed, 3560 insertions(+), 2970 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/configuration/Configuration.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/configuration/Configuration.java b/core/api/src/main/java/org/apache/zest/api/configuration/Configuration.java
index 6521c8b..9f6acc0 100644
--- a/core/api/src/main/java/org/apache/zest/api/configuration/Configuration.java
+++ b/core/api/src/main/java/org/apache/zest/api/configuration/Configuration.java
@@ -36,6 +36,7 @@ import org.apache.zest.api.unitofwork.EntityTypeNotFoundException;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.Usecase;
 import org.apache.zest.api.usecase.UsecaseBuilder;
 import org.apache.zest.api.value.ValueSerialization;
@@ -163,7 +164,7 @@ public interface Configuration<T>
         private ServiceComposite me;
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Service
         private Iterable<ServiceReference<ValueSerialization>> valueSerialization;
@@ -178,7 +179,7 @@ public interface Configuration<T>
             if( configuration == null )
             {
                 Usecase usecase = UsecaseBuilder.newUsecase( "Configuration:" + me.identity().get() );
-                uow = module.newUnitOfWork( usecase );
+                uow = uowf.newUnitOfWork( usecase );
                 try
                 {
                     configuration = this.findConfigurationInstanceFor( me, uow );
@@ -253,7 +254,7 @@ public interface Configuration<T>
         {
             Module module = api.moduleOf( serviceComposite );
             Usecase usecase = UsecaseBuilder.newUsecase( "Configuration:" + me.identity().get() );
-            UnitOfWork buildUow = module.newUnitOfWork( usecase );
+            UnitOfWork buildUow = module.unitOfWorkFactory().newUnitOfWork( usecase );
 
             Class<?> type = api.serviceDescriptorFor( serviceComposite ).types().findFirst().orElse( null );
             Class<V> configType = serviceModel.configurationType();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/entity/EntityBuilderTemplate.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/entity/EntityBuilderTemplate.java b/core/api/src/main/java/org/apache/zest/api/entity/EntityBuilderTemplate.java
index 56afa2c..850f54a 100644
--- a/core/api/src/main/java/org/apache/zest/api/entity/EntityBuilderTemplate.java
+++ b/core/api/src/main/java/org/apache/zest/api/entity/EntityBuilderTemplate.java
@@ -36,7 +36,7 @@ public abstract class EntityBuilderTemplate<T>
 
     public T newInstance( Module module )
     {
-        EntityBuilder<T> builder = module.currentUnitOfWork().newEntityBuilder( type );
+        EntityBuilder<T> builder = module.unitOfWorkFactory().currentUnitOfWork().newEntityBuilder( type );
         build( builder.instance() );
         return builder.newInstance();
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/structure/Module.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/structure/Module.java b/core/api/src/main/java/org/apache/zest/api/structure/Module.java
index e5a0aa6..38d8803 100644
--- a/core/api/src/main/java/org/apache/zest/api/structure/Module.java
+++ b/core/api/src/main/java/org/apache/zest/api/structure/Module.java
@@ -16,11 +16,8 @@ package org.apache.zest.api.structure;
 
 import java.util.stream.Stream;
 import org.apache.zest.api.activation.ActivationEventListenerRegistration;
-import org.apache.zest.api.composite.Composite;
 import org.apache.zest.api.composite.TransientBuilderFactory;
-import org.apache.zest.api.composite.TransientComposite;
 import org.apache.zest.api.composite.TransientDescriptor;
-import org.apache.zest.api.entity.EntityComposite;
 import org.apache.zest.api.entity.EntityDescriptor;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.object.ObjectDescriptor;
@@ -44,7 +41,6 @@ public interface Module
             ObjectFactory,
             TransientBuilderFactory,
             ValueBuilderFactory,
-            UnitOfWorkFactory,
             QueryBuilderFactory,
             ServiceFinder
 {
@@ -61,32 +57,43 @@ public interface Module
 
     /**
      * @param typeName name of a transient composite type
+     *
      * @return the descriptor for a transient composite or null if the class could not be found or the transient composite is not visible
      */
     TransientDescriptor transientDescriptor( String typeName );
 
     /**
      * @param typeName name of an entity composite type
+     *
      * @return the descriptor for an entity composite or null if the class could not be found or the entity composite is not visible
      */
     EntityDescriptor entityDescriptor( String typeName );
 
     /**
      * @param typeName name of an object type
+     *
      * @return the descriptor for an object or null if the class could not be found or the object is not visible
      */
     ObjectDescriptor objectDescriptor( String typeName );
 
     /**
      * @param typeName name of a value composite type
+     *
      * @return the descriptor for a value composite or null if the class could not be found or the value composite is not visible
      */
     ValueDescriptor valueDescriptor( String typeName );
 
     Stream<? extends TransientDescriptor> transientComposites();
+
     Stream<? extends ValueDescriptor> valueComposites();
+
     Stream<? extends ServiceDescriptor> serviceComposites();
+
     Stream<? extends EntityDescriptor> entityComposites();
+
     Stream<? extends ImportedServiceDescriptor> importedServices();
+
     Stream<? extends ObjectDescriptor> objects();
+
+    UnitOfWorkFactory unitOfWorkFactory();
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/type/HasTypes.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/type/HasTypes.java b/core/api/src/main/java/org/apache/zest/api/type/HasTypes.java
index 0bc0a35..0c3a0ac 100644
--- a/core/api/src/main/java/org/apache/zest/api/type/HasTypes.java
+++ b/core/api/src/main/java/org/apache/zest/api/type/HasTypes.java
@@ -18,6 +18,7 @@
  */
 package org.apache.zest.api.type;
 
+import java.lang.reflect.Type;
 import java.util.stream.Stream;
 
 /**
@@ -26,4 +27,9 @@ import java.util.stream.Stream;
 public interface HasTypes
 {
     Stream<Class<?>> types();
+
+    default boolean hasType( Type type )
+    {
+        return types().anyMatch( type::equals );
+    }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/type/ValueType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/type/ValueType.java b/core/api/src/main/java/org/apache/zest/api/type/ValueType.java
index dc28f10..80a2a81 100644
--- a/core/api/src/main/java/org/apache/zest/api/type/ValueType.java
+++ b/core/api/src/main/java/org/apache/zest/api/type/ValueType.java
@@ -14,6 +14,7 @@
  */
 package org.apache.zest.api.type;
 
+import java.lang.reflect.Type;
 import java.util.Collections;
 import java.util.List;
 import java.util.function.Function;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWork.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWork.java b/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWork.java
index d735afa..b218e6d 100644
--- a/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWork.java
+++ b/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWork.java
@@ -18,6 +18,7 @@ package org.apache.zest.api.unitofwork;
 import java.util.Map;
 import java.util.function.Function;
 import org.apache.zest.api.association.AssociationDescriptor;
+import org.apache.zest.api.common.Optional;
 import org.apache.zest.api.composite.AmbiguousTypeException;
 import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.entity.EntityReference;
@@ -147,7 +148,7 @@ public interface UnitOfWork extends MetaInfoHolder, AutoCloseable
      * @throws AmbiguousTypeException      If several mixins implement the given type
      * @throws LifecycleException          if the entity cannot be created
      */
-    <T> T newEntity( Class<T> type, String identity )
+    <T> T newEntity( Class<T> type, @Optional String identity )
         throws EntityTypeNotFoundException, AmbiguousTypeException, LifecycleException;
 
     /**
@@ -180,7 +181,7 @@ public interface UnitOfWork extends MetaInfoHolder, AutoCloseable
      * @throws EntityTypeNotFoundException if no EntityComposite type of the given mixin type has been registered
      * @throws AmbiguousTypeException      If several mixins implement the given type
      */
-    <T> EntityBuilder<T> newEntityBuilder( Class<T> type, String identity )
+    <T> EntityBuilder<T> newEntityBuilder( Class<T> type, @Optional String identity )
         throws EntityTypeNotFoundException, AmbiguousTypeException;
 
     /**
@@ -229,7 +230,7 @@ public interface UnitOfWork extends MetaInfoHolder, AutoCloseable
      * @throws EntityTypeNotFoundException If no mixins implements the given type
      * @throws AmbiguousTypeException      If several mixins implement the given type
      */
-    <T> EntityBuilder<T> newEntityBuilderWithState( Class<T> type, String identity,
+    <T> EntityBuilder<T> newEntityBuilderWithState( Class<T> type, @Optional String identity,
                                                     Function<PropertyDescriptor, Object> propertyFunction,
                                                     Function<AssociationDescriptor, EntityReference> associationFunction,
                                                     Function<AssociationDescriptor, Iterable<EntityReference>> manyAssociationFunction,

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWorkTemplate.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWorkTemplate.java b/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWorkTemplate.java
index cd91cb9..2d5be61 100644
--- a/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWorkTemplate.java
+++ b/core/api/src/main/java/org/apache/zest/api/unitofwork/UnitOfWorkTemplate.java
@@ -58,7 +58,7 @@ public abstract class UnitOfWorkTemplate<RESULT, ThrowableType extends Throwable
         ThrowableType ex = null;
         do
         {
-            UnitOfWork uow = module.newUnitOfWork( usecase );
+            UnitOfWork uow = module.unitOfWorkFactory().newUnitOfWork( usecase );
 
             try
             {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/main/java/org/apache/zest/api/unitofwork/concern/UnitOfWorkConcern.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/zest/api/unitofwork/concern/UnitOfWorkConcern.java b/core/api/src/main/java/org/apache/zest/api/unitofwork/concern/UnitOfWorkConcern.java
index c79db85..ec6d54d 100644
--- a/core/api/src/main/java/org/apache/zest/api/unitofwork/concern/UnitOfWorkConcern.java
+++ b/core/api/src/main/java/org/apache/zest/api/unitofwork/concern/UnitOfWorkConcern.java
@@ -23,9 +23,9 @@ import org.apache.zest.api.common.AppliesTo;
 import org.apache.zest.api.concern.GenericConcern;
 import org.apache.zest.api.injection.scope.Invocation;
 import org.apache.zest.api.injection.scope.Structure;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.ConcurrentEntityModificationException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.Usecase;
 import org.apache.zest.api.usecase.UsecaseBuilder;
 
@@ -42,10 +42,10 @@ public class UnitOfWorkConcern
     private static final Class<?>[] DEFAULT_DISCARD_CLASSES = new Class[]{ Throwable.class };
 
     @Structure
-    Module module;
+    private UnitOfWorkFactory uowf;
 
     @Invocation
-    UnitOfWorkPropagation propagation;
+    private UnitOfWorkPropagation propagation;
 
     /**
      * Handles method with {@code UnitOfWorkPropagation} annotation.
@@ -65,7 +65,7 @@ public class UnitOfWorkConcern
         UnitOfWorkPropagation.Propagation propagationPolicy = propagation.value();
         if( propagationPolicy == UnitOfWorkPropagation.Propagation.REQUIRED )
         {
-            if( module.isUnitOfWorkActive() )
+            if( uowf.isUnitOfWorkActive() )
             {
                 //noinspection ConstantConditions
                 return next.invoke( proxy, method, args );
@@ -73,12 +73,12 @@ public class UnitOfWorkConcern
             else
             {
                 Usecase usecase = usecase();
-                return invokeWithCommit( proxy, method, args, module.newUnitOfWork( usecase ) );
+                return invokeWithCommit( proxy, method, args, uowf.newUnitOfWork( usecase ) );
             }
         }
         else if( propagationPolicy == UnitOfWorkPropagation.Propagation.MANDATORY )
         {
-            if( !module.isUnitOfWorkActive() )
+            if( !uowf.isUnitOfWorkActive() )
             {
                 throw new IllegalStateException( "UnitOfWork was required but there is no available unit of work." );
             }
@@ -86,7 +86,7 @@ public class UnitOfWorkConcern
         else if( propagationPolicy == UnitOfWorkPropagation.Propagation.REQUIRES_NEW )
         {
             Usecase usecase = usecase();
-            return invokeWithCommit( proxy, method, args, module.newUnitOfWork( usecase ) );
+            return invokeWithCommit( proxy, method, args, uowf.newUnitOfWork( usecase ) );
         }
         //noinspection ConstantConditions
         return next.invoke( proxy, method, args );
@@ -132,7 +132,7 @@ public class UnitOfWorkConcern
                     currentUnitOfWork.complete();
                     return result;
                 }
-                catch( UndeclaredThrowableException e)
+                catch( UndeclaredThrowableException e )
                 {
                     Throwable undeclared = e.getUndeclaredThrowable();
                     if( undeclared instanceof ConcurrentEntityModificationException )
@@ -173,9 +173,9 @@ public class UnitOfWorkConcern
         {
             throw e;
         }
-        module.currentUnitOfWork().discard();
+        uowf.currentUnitOfWork().discard();
         Thread.sleep( initialDelay + retry * delayFactor );
-        return module.newUnitOfWork( usecase() );
+        return uowf.newUnitOfWork( usecase() );
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/test/java/org/apache/zest/api/OperatorsTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/zest/api/OperatorsTest.java b/core/api/src/test/java/org/apache/zest/api/OperatorsTest.java
index 0f917d6..2214433 100644
--- a/core/api/src/test/java/org/apache/zest/api/OperatorsTest.java
+++ b/core/api/src/test/java/org/apache/zest/api/OperatorsTest.java
@@ -19,6 +19,8 @@
 package org.apache.zest.api;
 
 import java.util.function.Predicate;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Assert;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
@@ -58,10 +60,12 @@ public class OperatorsTest
                 module.values( TestValue.class );
                 module.forMixin( TestEntity.class ).declareDefaults().foo().set( "Bar" );
                 module.forMixin( TestValue.class ).declareDefaults().bar().set( "Xyz" );
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
         };
 
-        UnitOfWork uow = assembler.module().newUnitOfWork();
+        UnitOfWorkFactory uowf = assembler.module().unitOfWorkFactory();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         try
         {
@@ -70,7 +74,7 @@ public class OperatorsTest
             TestEntity testEntity = entityBuilder.newInstance();
 
             uow.complete();
-            uow = assembler.module().newUnitOfWork();
+            uow = uowf.newUnitOfWork();
 
             Iterable<TestEntity> entities = Iterables.iterable( testEntity = uow.get( testEntity ) );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/test/java/org/apache/zest/api/injection/scope/StateFieldTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/zest/api/injection/scope/StateFieldTest.java b/core/api/src/test/java/org/apache/zest/api/injection/scope/StateFieldTest.java
index 02fc6ae..a1c80de 100644
--- a/core/api/src/test/java/org/apache/zest/api/injection/scope/StateFieldTest.java
+++ b/core/api/src/test/java/org/apache/zest/api/injection/scope/StateFieldTest.java
@@ -46,7 +46,7 @@ public class StateFieldTest
     public void givenEntityWithFieldPropertiesWhenUpdatedThenReturnCorrect()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             PersonEntity charles = unitOfWork.newEntity( PersonEntity.class );
@@ -67,7 +67,7 @@ public class StateFieldTest
 
             unitOfWork.complete();
 
-            unitOfWork = module.newUnitOfWork();
+            unitOfWork = uowf.newUnitOfWork();
 
             charles = unitOfWork.get( charles );
             daniel = unitOfWork.get( daniel );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/test/java/org/apache/zest/api/property/PropertyErrorTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/zest/api/property/PropertyErrorTest.java b/core/api/src/test/java/org/apache/zest/api/property/PropertyErrorTest.java
index 22488fa..b4969a1 100644
--- a/core/api/src/test/java/org/apache/zest/api/property/PropertyErrorTest.java
+++ b/core/api/src/test/java/org/apache/zest/api/property/PropertyErrorTest.java
@@ -40,7 +40,7 @@ public class PropertyErrorTest
     public void givenEntityWithNonOptionPropertyWhenInstantiatedThenException()
         throws Exception
     {
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             PersonEntity person = unitOfWork.newEntity( PersonEntity.class );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/test/java/org/apache/zest/api/unitofwork/RemovalTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/zest/api/unitofwork/RemovalTest.java b/core/api/src/test/java/org/apache/zest/api/unitofwork/RemovalTest.java
index 9f80c4f..745cfb2 100644
--- a/core/api/src/test/java/org/apache/zest/api/unitofwork/RemovalTest.java
+++ b/core/api/src/test/java/org/apache/zest/api/unitofwork/RemovalTest.java
@@ -43,7 +43,7 @@ public class RemovalTest
     public void givenEntityIsCreatedAndUnitOfWorkIsNotCompletedWhenEntityIsRemoveThenSuccessfulRemoval()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<TestEntity> builder = uow.newEntityBuilder( TestEntity.class, "123" );
@@ -62,7 +62,7 @@ public class RemovalTest
     public void givenStandardPidRegulatorWhenNoChangeInInputExpectOutputToGoTowardsMinimum()
         throws Exception
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         PidRegulator regulator = null;
         try
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/test/java/org/apache/zest/api/value/DocumentationSupport.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/zest/api/value/DocumentationSupport.java b/core/api/src/test/java/org/apache/zest/api/value/DocumentationSupport.java
index 43acbc2..e85e2fc 100644
--- a/core/api/src/test/java/org/apache/zest/api/value/DocumentationSupport.java
+++ b/core/api/src/test/java/org/apache/zest/api/value/DocumentationSupport.java
@@ -28,25 +28,23 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.function.Function;
-import org.junit.Before;
-import org.junit.Test;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.property.Property;
 import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.type.CollectionType;
-import org.apache.zest.bootstrap.ApplicationAssembler;
-import org.apache.zest.bootstrap.ApplicationAssembly;
-import org.apache.zest.bootstrap.ApplicationAssemblyFactory;
 import org.apache.zest.bootstrap.Assembler;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.Energy4Java;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.io.Inputs;
 import org.apache.zest.io.Outputs;
 import org.apache.zest.io.Transforms;
 import org.apache.zest.test.AbstractZestTest;
 import org.apache.zest.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.Before;
+import org.junit.Test;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.junit.Assert.assertThat;
@@ -82,6 +80,7 @@ public class DocumentationSupport
         module.values( SomeValue.class ); // (2)
         // END SNIPPET: default
         new OrgJsonValueSerializationAssembler().assemble( module ); // (3)
+        new DefaultUnitOfWorkAssembler().assemble( module );
         // START SNIPPET: default
     }
     // END SNIPPET: default
@@ -101,6 +100,7 @@ public class DocumentationSupport
 
         // START SNIPPET: default
     }
+
     // END SNIPPET: default
     // START SNIPPET: service
     @Service
@@ -217,56 +217,39 @@ public class DocumentationSupport
     public void assembledWithValuesModuleSerialization()
         throws Exception
     {
-        Application app = new Energy4Java().newApplication( new ApplicationAssembler()
-        {
-            @Override
-            public ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
-                throws AssemblyException
-            {
-                Assembler[][][] pancakes = new Assembler[][][]
+        Application app = new Energy4Java().newApplication( applicationFactory -> {
+            Assembler[][][] pancakes = new Assembler[][][]
                 {
                     {
                         {
-                            new Assembler()
-                            {
-                                @Override
-                                public void assemble( ModuleAssembly valuesModule )
-                                    throws AssemblyException
-                                {
-                                    valuesModule.layer().setName( "SINGLE-Layer" );
-                                    valuesModule.setName( "VALUES-Module" );
+                            valuesModule -> {
+                                valuesModule.layer().setName( "SINGLE-Layer" );
+                                valuesModule.setName( "VALUES-Module" );
 
-                                    valuesModule.values( SomeValue.class );
-                                }
+                                valuesModule.values( SomeValue.class );
+                                new DefaultUnitOfWorkAssembler().assemble( valuesModule );
                             }
                         },
                         {
-                            new Assembler()
-                            {
-                                @Override
-                                public void assemble( ModuleAssembly servicesModule )
-                                    throws AssemblyException
-                                {
-                                    servicesModule.setName( "SERVICES-Module" );
+                            servicesModule -> {
+                                servicesModule.setName( "SERVICES-Module" );
 
-                                    Function<Application, Module> valuesModuleFinder = new Function<Application, Module>()
+                                Function<Application, Module> valuesModuleFinder = new Function<Application, Module>()
+                                {
+                                    @Override
+                                    public Module apply( Application app1 )
                                     {
-                                        @Override
-                                        public Module apply( Application app )
-                                        {
-                                            return app.findModule( "SINGLE-Layer", "VALUES-Module" );
-                                        }
-                                    };
-                                    new OrgJsonValueSerializationAssembler().
-                                        withValuesModuleFinder( valuesModuleFinder ).
-                                        assemble( servicesModule );
-                                }
+                                        return app1.findModule( "SINGLE-Layer", "VALUES-Module" );
+                                    }
+                                };
+                                new OrgJsonValueSerializationAssembler().
+                                    withValuesModuleFinder( valuesModuleFinder ).
+                                    assemble( servicesModule );
                             }
                         }
                     }
                 };
-                return applicationFactory.newApplicationAssembly( pancakes );
-            }
+            return applicationFactory.newApplicationAssembly( pancakes );
         } );
         app.activate();
         try

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/api/src/test/java/org/apache/zest/api/value/ValueCompositeTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/zest/api/value/ValueCompositeTest.java b/core/api/src/test/java/org/apache/zest/api/value/ValueCompositeTest.java
index 89f75df..b5499c4 100644
--- a/core/api/src/test/java/org/apache/zest/api/value/ValueCompositeTest.java
+++ b/core/api/src/test/java/org/apache/zest/api/value/ValueCompositeTest.java
@@ -184,7 +184,7 @@ public class ValueCompositeTest
         builder.prototype().number().set( 42L );
         SomeValue some = builder.newInstance();
 
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<SomeEntity> entityBuilder = unitOfWork.newEntityBuilder( SomeEntity.class );
@@ -213,7 +213,7 @@ public class ValueCompositeTest
         builder.prototype().number().set( 42L );
         SomeValue some = builder.newInstance();
 
-        UnitOfWork unitOfWork = module.newUnitOfWork();
+        UnitOfWork unitOfWork = uowf.newUnitOfWork();
         AssociationValue associationValue;
         try
         {
@@ -229,7 +229,7 @@ public class ValueCompositeTest
 
             unitOfWork.complete();
 
-            unitOfWork = module.newUnitOfWork();
+            unitOfWork = uowf.newUnitOfWork();
 
             AssociationValue newAssociationValue = module.newValueFromSerializedState( AssociationValue.class, json );
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/bootstrap/src/main/java/org/apache/zest/bootstrap/ModuleAssembly.java
----------------------------------------------------------------------
diff --git a/core/bootstrap/src/main/java/org/apache/zest/bootstrap/ModuleAssembly.java b/core/bootstrap/src/main/java/org/apache/zest/bootstrap/ModuleAssembly.java
index f99c506..bdd8828 100644
--- a/core/bootstrap/src/main/java/org/apache/zest/bootstrap/ModuleAssembly.java
+++ b/core/bootstrap/src/main/java/org/apache/zest/bootstrap/ModuleAssembly.java
@@ -23,6 +23,7 @@ import java.util.function.Predicate;
 import org.apache.zest.api.activation.Activator;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.type.HasTypes;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 
 /**
  * The ModuleAssembly is used to register any information about * what the module should contain, such as composites,
@@ -77,10 +78,42 @@ public interface ModuleAssembly
      *
      * @return the assembly
      */
-    @SuppressWarnings({ "unchecked", "varargs" })
+    @SuppressWarnings( { "unchecked", "varargs" } )
     ModuleAssembly withActivators( Class<? extends Activator<Module>>... activators );
 
     /**
+     * Adds the default UnitOfWorkFactory to this Module.
+     * <p>
+     * In versions &lt;3.0, UnitOfWork was built into the Core Runtime, and couldn't be custom made. In 3.0, the
+     * UnitOfWorkFactory is a regular Service that the Module instance will look up on demand.
+     * </p>
+     * <p>
+     * Typically, this method should be called, and it should be called first in the Assembler, so that
+     * it is possible to add Concerns and SideEffects to the default implementation of either the
+     * {@link org.apache.zest.api.unitofwork.UnitOfWorkFactory} or the
+     * {@link org.apache.zest.api.unitofwork.UnitOfWork}.
+     * </p>
+     * <p>
+     * Internally, this method is the equivalent of;
+     * </p>
+     * <pre><code>
+     *     new DefaultUnitOfWorkAssembler().assemble( module );
+     * </code>
+     * </pre>
+     * <p>
+     * and the {@link DefaultUnitOfWorkAssembler} does the equivalent of
+     * </p>
+     * <pre><code>
+     *     module.services( UnitOfWorkFactory.class ).withMixins( UnitOfWorkFactoryMixin.class );
+     *     module.transients( UnitOfWork.class ).withMixins( ModuleUnitOfWork.class );
+     * </code></pre>
+     * albeit those Mixins are in the Core Runtime and since Core Runtime is not a direct dependency of any
+     * other module, the classes are loaded with reflection. This may change in the future.
+     */
+    ModuleAssembly withDefaultUnitOfWorkFactory()
+        throws AssemblyException;
+
+    /**
      * Declare a list of TransientComposites for this Module. Use the TransientDeclaration that is returned to
      * declare further settings. Note that the TransientDeclaration works on all of the types specified.
      *
@@ -160,7 +193,6 @@ public interface ModuleAssembly
      */
     ConfigurationDeclaration configurations( Predicate<HasTypes> specification );
 
-
     /**
      * Declare a list of object classes for this Module. Use the ObjectDeclaration that is returned to
      * declare further settings. Note that the ObjectDeclaration works on all of the types specified.

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/bootstrap/src/main/java/org/apache/zest/bootstrap/unitofwork/DefaultUnitOfWorkAssembler.java
----------------------------------------------------------------------
diff --git a/core/bootstrap/src/main/java/org/apache/zest/bootstrap/unitofwork/DefaultUnitOfWorkAssembler.java b/core/bootstrap/src/main/java/org/apache/zest/bootstrap/unitofwork/DefaultUnitOfWorkAssembler.java
new file mode 100644
index 0000000..14171cd
--- /dev/null
+++ b/core/bootstrap/src/main/java/org/apache/zest/bootstrap/unitofwork/DefaultUnitOfWorkAssembler.java
@@ -0,0 +1,55 @@
+/*
+ * 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.zest.bootstrap.unitofwork;
+
+import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.apache.zest.bootstrap.Assembler;
+import org.apache.zest.bootstrap.AssemblyException;
+import org.apache.zest.bootstrap.ModuleAssembly;
+
+public class DefaultUnitOfWorkAssembler
+    implements Assembler
+{
+    @Override
+    public void assemble( ModuleAssembly module )
+        throws AssemblyException
+    {
+        Class factoryMixin = loadMixinClass( "org.apache.zest.runtime.unitofwork.UnitOfWorkFactoryMixin" );
+        module.services( UnitOfWorkFactory.class ).withMixins( factoryMixin );
+
+        Class uowMixin = loadMixinClass( "org.apache.zest.runtime.unitofwork.ModuleUnitOfWork" );
+        module.transients( UnitOfWork.class ).withMixins( uowMixin );
+    }
+
+    private Class<?> loadMixinClass( String name )
+        throws AssemblyException
+    {
+        try
+        {
+            return getClass().getClassLoader().loadClass( name );
+        }
+        catch( ClassNotFoundException e )
+        {
+            throw new AssemblyException( "Default UnitOfWorkFactory mixin is not present in the system." );
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/bootstrap/src/test/java/org/apache/zest/bootstrap/ClassScannerTest.java
----------------------------------------------------------------------
diff --git a/core/bootstrap/src/test/java/org/apache/zest/bootstrap/ClassScannerTest.java b/core/bootstrap/src/test/java/org/apache/zest/bootstrap/ClassScannerTest.java
index fc7147b..90b6d5a 100644
--- a/core/bootstrap/src/test/java/org/apache/zest/bootstrap/ClassScannerTest.java
+++ b/core/bootstrap/src/test/java/org/apache/zest/bootstrap/ClassScannerTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.zest.bootstrap;
 
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Assert;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
@@ -48,6 +49,7 @@ public class ClassScannerTest
                 for( Class aClass : filter( matches( ".*Value" ), findClasses( TestValue.class ) ) )
                 {
                     module.values( aClass );
+                    new DefaultUnitOfWorkAssembler().assemble( module );
                 }
             }
         };

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/ZestRuntimeImpl.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/ZestRuntimeImpl.java b/core/runtime/src/main/java/org/apache/zest/runtime/ZestRuntimeImpl.java
index ac931fa..ce9a239 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/ZestRuntimeImpl.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/ZestRuntimeImpl.java
@@ -62,7 +62,7 @@ import org.apache.zest.runtime.property.PropertyInstance;
 import org.apache.zest.runtime.service.ImportedServiceReferenceInstance;
 import org.apache.zest.runtime.service.ServiceInstance;
 import org.apache.zest.runtime.service.ServiceReferenceInstance;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.runtime.unitofwork.ModuleUnitOfWork;
 import org.apache.zest.runtime.value.ValueInstance;
 import org.apache.zest.spi.ZestSPI;
 import org.apache.zest.spi.entity.EntityState;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationModel.java
index 57c6790..cdc3198 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationModel.java
@@ -44,13 +44,10 @@ import org.apache.zest.functional.Visitor;
 import org.apache.zest.runtime.composite.ValueConstraintsInstance;
 import org.apache.zest.runtime.model.Binder;
 import org.apache.zest.runtime.model.Resolution;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.runtime.unitofwork.ModuleUnitOfWork;
 import org.apache.zest.runtime.unitofwork.BuilderEntityState;
 import org.apache.zest.spi.entity.EntityState;
 
-import static org.apache.zest.functional.Iterables.empty;
-import static org.apache.zest.functional.Iterables.first;
-
 /**
  * Model for a ManyAssociation.
  *

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationsModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationsModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationsModel.java
index 11d188d..0df3b35 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationsModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/association/ManyAssociationsModel.java
@@ -27,7 +27,7 @@ import org.apache.zest.api.association.ManyAssociation;
 import org.apache.zest.api.common.QualifiedName;
 import org.apache.zest.functional.HierarchicalVisitor;
 import org.apache.zest.functional.VisitableHierarchy;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.runtime.unitofwork.ModuleUnitOfWork;
 import org.apache.zest.runtime.value.ValueStateInstance;
 import org.apache.zest.spi.entity.EntityState;
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationModel.java
index 0b0f340..a930f48 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationModel.java
@@ -45,13 +45,10 @@ import org.apache.zest.functional.Visitor;
 import org.apache.zest.runtime.composite.ValueConstraintsInstance;
 import org.apache.zest.runtime.model.Binder;
 import org.apache.zest.runtime.model.Resolution;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.runtime.unitofwork.ModuleUnitOfWork;
 import org.apache.zest.runtime.unitofwork.BuilderEntityState;
 import org.apache.zest.spi.entity.EntityState;
 
-import static org.apache.zest.functional.Iterables.empty;
-import static org.apache.zest.functional.Iterables.first;
-
 /**
  * Model for a NamedAssociation.
  *

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationsModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationsModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationsModel.java
index ad536d1..6c1783b 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationsModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/association/NamedAssociationsModel.java
@@ -28,7 +28,7 @@ import org.apache.zest.api.association.NamedAssociation;
 import org.apache.zest.api.common.QualifiedName;
 import org.apache.zest.functional.HierarchicalVisitor;
 import org.apache.zest.functional.VisitableHierarchy;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.runtime.unitofwork.ModuleUnitOfWork;
 import org.apache.zest.runtime.value.ValueStateInstance;
 import org.apache.zest.spi.entity.EntityState;
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/CompositeAssemblyImpl.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/CompositeAssemblyImpl.java b/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/CompositeAssemblyImpl.java
index 9190d67f..c7308f7 100755
--- a/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/CompositeAssemblyImpl.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/CompositeAssemblyImpl.java
@@ -18,9 +18,31 @@
  */
 package org.apache.zest.runtime.bootstrap;
 
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Consumer;
 import java.util.function.Function;
-import org.apache.zest.api.common.*;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.zest.api.common.MetaInfo;
 import org.apache.zest.api.common.Optional;
+import org.apache.zest.api.common.QualifiedName;
+import org.apache.zest.api.common.UseDefaults;
+import org.apache.zest.api.common.Visibility;
 import org.apache.zest.api.composite.InvalidCompositeException;
 import org.apache.zest.api.concern.Concerns;
 import org.apache.zest.api.constraint.Constraint;
@@ -42,24 +64,40 @@ import org.apache.zest.api.util.Classes;
 import org.apache.zest.api.util.Fields;
 import org.apache.zest.bootstrap.StateDeclarations;
 import org.apache.zest.functional.HierarchicalVisitorAdapter;
-import org.apache.zest.runtime.composite.*;
+import org.apache.zest.runtime.composite.AbstractConstraintModel;
+import org.apache.zest.runtime.composite.CompositeConstraintModel;
+import org.apache.zest.runtime.composite.CompositeMethodModel;
+import org.apache.zest.runtime.composite.CompositeMethodsModel;
+import org.apache.zest.runtime.composite.ConcernModel;
+import org.apache.zest.runtime.composite.ConcernsModel;
+import org.apache.zest.runtime.composite.ConstraintModel;
+import org.apache.zest.runtime.composite.ConstraintsModel;
+import org.apache.zest.runtime.composite.Genericpredicate;
+import org.apache.zest.runtime.composite.MixinModel;
+import org.apache.zest.runtime.composite.MixinsModel;
+import org.apache.zest.runtime.composite.SideEffectModel;
+import org.apache.zest.runtime.composite.SideEffectsModel;
+import org.apache.zest.runtime.composite.StateModel;
+import org.apache.zest.runtime.composite.ValueConstraintsInstance;
+import org.apache.zest.runtime.composite.ValueConstraintsModel;
 import org.apache.zest.runtime.injection.Dependencies;
 import org.apache.zest.runtime.injection.DependencyModel;
 import org.apache.zest.runtime.property.PropertiesModel;
 import org.apache.zest.runtime.property.PropertyModel;
 
-import java.lang.annotation.Annotation;
-import java.lang.reflect.*;
-import java.util.*;
-import java.util.function.Consumer;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
 import static java.util.stream.Stream.concat;
-import static org.apache.zest.api.util.Annotations.*;
-import static org.apache.zest.api.util.Classes.*;
-import static org.apache.zest.functional.Iterables.*;
+import static org.apache.zest.api.util.Annotations.hasAnnotation;
+import static org.apache.zest.api.util.Annotations.isType;
+import static org.apache.zest.api.util.Annotations.type;
+import static org.apache.zest.api.util.Classes.classHierarchy;
+import static org.apache.zest.api.util.Classes.interfacesOf;
+import static org.apache.zest.api.util.Classes.isAssignableFrom;
+import static org.apache.zest.api.util.Classes.typeOf;
+import static org.apache.zest.api.util.Classes.typesOf;
+import static org.apache.zest.api.util.Classes.wrapperClass;
+import static org.apache.zest.functional.Iterables.filter;
+import static org.apache.zest.functional.Iterables.first;
+import static org.apache.zest.functional.Iterables.iterable;
 import static org.apache.zest.runtime.legacy.Specifications.translate;
 
 /**
@@ -211,8 +249,9 @@ public abstract class CompositeAssemblyImpl
 
                     interfacesOf( mixinModel.mixinClass() )
                         .map( Classes.RAW_CLASS )
-                        .filter( clazz -> Stream.of( Initializable.class, Lifecycle.class, InvocationHandler.class ).noneMatch( c -> c
-                            .equals( clazz ) ) )
+                        .filter( clazz -> Stream.of( Initializable.class, Lifecycle.class, InvocationHandler.class )
+                            .noneMatch( c -> c
+                                .equals( clazz ) ) )
                         .forEach( thisDependencies::add );
 
 //                    // Implement @This references
@@ -220,7 +259,6 @@ public abstract class CompositeAssemblyImpl
 //                                                  filter( new DependencyModel.ScopeSpecification( This.class ),
 //                                                          methodComposite.dependencies() ) );
 
-
 //                    Iterable<Class<?>> map1 = map( new DependencyModel.InjectionTypeFunction(),
 //                                                   filter( new DependencyModel.ScopeSpecification( This.class ),
 //                                                           mixinModel.dependencies() ) );
@@ -257,10 +295,10 @@ public abstract class CompositeAssemblyImpl
                 mixinDeclarations( thisDependency ) );
             List<? extends Class<?>> singleton = Collections.singletonList( thisDependency );
             implementMixinType( singleton,
-                                toList(typeConstraintClasses),
-                                toList(typeConcernClasses),
-                                toList(typeSideEffectClasses),
-                                toList(typeMixinClasses)
+                                toList( typeConstraintClasses ),
+                                toList( typeConcernClasses ),
+                                toList( typeSideEffectClasses ),
+                                toList( typeMixinClasses )
             );
         } );
     }
@@ -393,15 +431,15 @@ public abstract class CompositeAssemblyImpl
                                               List<Class<?>> constraintClasses
     )
     {
-        List<Annotation> annotations = Annotations.findAccessorAndTypeAnnotationsIn(accessor);
-        boolean optional = annotations.stream().anyMatch(isType(Optional.class));
+        List<Annotation> annotations = Annotations.findAccessorAndTypeAnnotationsIn( accessor );
+        boolean optional = annotations.stream().anyMatch( isType( Optional.class ) );
         ValueConstraintsModel valueConstraintsModel = constraintsFor(
-                annotations.stream(),
-                GenericPropertyInfo.propertyTypeOf(accessor),
-                ((Member) accessor).getName(),
-                optional,
-                constraintClasses,
-                accessor);
+            annotations.stream(),
+            GenericPropertyInfo.propertyTypeOf( accessor ),
+            ( (Member) accessor ).getName(),
+            optional,
+            constraintClasses,
+            accessor );
         ValueConstraintsInstance valueConstraintsInstance = null;
         if( valueConstraintsModel.isConstrained() )
         {
@@ -552,7 +590,7 @@ public abstract class CompositeAssemblyImpl
         concernClasses.forEach( concern -> {
             if( helper.appliesTo( concern, method, types, mixinClass ) )
             {
-                concernsFor.add( helper.getConcernModel( concern ) );
+                addConcernIfNotExists( concernsFor, helper.getConcernModel( concern ) );
             }
             else
             {
@@ -564,7 +602,7 @@ public abstract class CompositeAssemblyImpl
                         Method mixinMethod = mixinClass.getMethod( method.getName(), method.getParameterTypes() );
                         if( helper.appliesTo( concern, mixinMethod, types, mixinClass ) )
                         {
-                            concernsFor.add( helper.getConcernModel( concern ) );
+                            addConcernIfNotExists( concernsFor, helper.getConcernModel( concern ) );
                         }
                     }
                     catch( NoSuchMethodException e )
@@ -586,7 +624,8 @@ public abstract class CompositeAssemblyImpl
                 {
                     if( helper.appliesTo( concern, method, types, mixinClass ) )
                     {
-                        concernsFor.add( helper.getConcernModel( concern ) );
+                        ConcernModel concernModel = helper.getConcernModel( concern );
+                        addConcernIfNotExists( concernsFor, concernModel );
                     }
                 }
             }
@@ -602,6 +641,14 @@ public abstract class CompositeAssemblyImpl
         }
     }
 
+    private void addConcernIfNotExists( List<ConcernModel> concernsFor, ConcernModel concernModel )
+    {
+        if( !concernsFor.contains( concernModel ) )
+        {
+            concernsFor.add( concernModel );
+        }
+    }
+
     private SideEffectsModel sideEffectsFor( Method method,
                                              Class<?> mixinClass,
                                              Stream<Class<?>> sideEffectClasses
@@ -609,9 +656,10 @@ public abstract class CompositeAssemblyImpl
     {
         List<SideEffectModel> sideEffectsFor = new ArrayList<>();
         sideEffectClasses.forEach( sideEffect -> {
+            SideEffectModel sideEffectModel = helper.getSideEffectModel( sideEffect );
             if( helper.appliesTo( sideEffect, method, types, mixinClass ) )
             {
-                sideEffectsFor.add( helper.getSideEffectModel( sideEffect ) );
+                addSideEffectIfNotExists( sideEffectsFor, sideEffectModel );
             }
             else
             {
@@ -623,7 +671,7 @@ public abstract class CompositeAssemblyImpl
                         Method mixinMethod = mixinClass.getMethod( method.getName(), method.getParameterTypes() );
                         if( helper.appliesTo( sideEffect, mixinMethod, types, mixinClass ) )
                         {
-                            sideEffectsFor.add( helper.getSideEffectModel( sideEffect ) );
+                            addSideEffectIfNotExists( sideEffectsFor, sideEffectModel );
                         }
                     }
                     catch( NoSuchMethodException e )
@@ -634,6 +682,25 @@ public abstract class CompositeAssemblyImpl
             }
         } );
 
+        // Check annotations on method that have @Concerns annotations themselves
+        for( Annotation annotation : method.getAnnotations() )
+        {
+            @SuppressWarnings( "raw" )
+            SideEffects sideEffects = annotation.annotationType().getAnnotation( SideEffects.class );
+            if( sideEffects != null )
+            {
+                for( Class<?> sideEffect : sideEffects.value() )
+                {
+                    if( helper.appliesTo( sideEffect, method, types, mixinClass ) )
+                    {
+                        SideEffectModel sideEffectModel = helper.getSideEffectModel( sideEffect );
+                        addSideEffectIfNotExists( sideEffectsFor, sideEffectModel );
+                    }
+                }
+            }
+        }
+
+
         if( sideEffectsFor.isEmpty() )
         {
             return SideEffectsModel.EMPTY_SIDEEFFECTS;
@@ -644,6 +711,14 @@ public abstract class CompositeAssemblyImpl
         }
     }
 
+    private void addSideEffectIfNotExists( List<SideEffectModel> sideEffectsFor, SideEffectModel sideEffectModel )
+    {
+        if( !sideEffectsFor.contains( sideEffectModel ) )
+        {
+            sideEffectsFor.add( sideEffectModel );
+        }
+    }
+
     @SuppressWarnings( "unchecked" )
     private Stream<Class<?>> constraintDeclarations( Class<?> type )
     {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/ModuleAssemblyImpl.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/ModuleAssemblyImpl.java b/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/ModuleAssemblyImpl.java
index b1d60d6..c06a811 100755
--- a/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/ModuleAssemblyImpl.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/bootstrap/ModuleAssemblyImpl.java
@@ -57,6 +57,7 @@ import org.apache.zest.bootstrap.TransientAssembly;
 import org.apache.zest.bootstrap.TransientDeclaration;
 import org.apache.zest.bootstrap.ValueAssembly;
 import org.apache.zest.bootstrap.ValueDeclaration;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.functional.Iterables;
 import org.apache.zest.runtime.activation.ActivatorsModel;
 import org.apache.zest.runtime.composite.TransientModel;
@@ -145,6 +146,14 @@ public final class ModuleAssemblyImpl
     }
 
     @Override
+    public ModuleAssembly withDefaultUnitOfWorkFactory()
+        throws AssemblyException
+    {
+        new DefaultUnitOfWorkAssembler().assemble( this );
+        return this;
+    }
+
+    @Override
     @SuppressWarnings( { "raw", "unchecked" } )
     public ValueDeclaration values( Class<?>... valueTypes )
     {
@@ -603,7 +612,8 @@ public final class ModuleAssemblyImpl
     private String generateId( Stream<Class<?>> serviceTypes )
     {
         // Find service identity that is not yet used
-        Class<?> serviceType = serviceTypes.findFirst().orElse( null ); // Use the first, which *SHOULD* be the main serviceType
+        Class<?> serviceType = serviceTypes.findFirst()
+            .orElse( null ); // Use the first, which *SHOULD* be the main serviceType
         int idx = 0;
         String id = serviceType.getSimpleName();
         boolean invalid;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/composite/CompositeModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/composite/CompositeModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/composite/CompositeModel.java
index e7f477e..7bd02ef 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/composite/CompositeModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/composite/CompositeModel.java
@@ -145,8 +145,8 @@ public abstract class CompositeModel
     @Override
     public Stream<DependencyModel> dependencies()
     {
-        return Stream.of( mixinsModel, compositeMethodsModel ).flatMap( Dependencies::dependencies );
-//        return Iterables.flatten( mixinsModel.dependencies(), compositeMethodsModel.dependencies() );
+        Stream<Dependencies> models = Stream.of( this.mixinsModel, compositeMethodsModel );
+        return models.flatMap( Dependencies::dependencies );
     }
 
     @Override
@@ -219,7 +219,6 @@ public abstract class CompositeModel
         Class<?> mainType = first( types );
         if( mainType.isInterface() )
         {
-
             try
             {
                 return Composite.class.cast( proxyConstructor.newInstance( invocationHandler ) );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientBuilderInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientBuilderInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientBuilderInstance.java
index 78be044..2b0570c 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientBuilderInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientBuilderInstance.java
@@ -19,7 +19,7 @@ import org.apache.zest.api.composite.CompositeInstance;
 import org.apache.zest.api.composite.TransientBuilder;
 import org.apache.zest.api.composite.TransientDescriptor;
 import org.apache.zest.runtime.property.PropertyInstance;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 import org.apache.zest.spi.module.ModuleSpi;
 
 /**

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientClassLoader.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientClassLoader.java b/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientClassLoader.java
index 384f4fc..53f0a6b 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientClassLoader.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/composite/TransientClassLoader.java
@@ -19,6 +19,7 @@ import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
 import java.util.List;
+import org.apache.zest.api.composite.Composite;
 import org.apache.zest.api.entity.Lifecycle;
 import org.apache.zest.api.mixin.Initializable;
 import org.apache.zest.api.util.Methods;
@@ -160,7 +161,7 @@ import static org.objectweb.asm.Type.getInternalName;
         AnnotationVisitor av0;
 
         // Class definition start
-        cw.visit( JDK_VERSION, ACC_PUBLIC + ACC_SUPER, classSlash, null, baseClassSlash, null );
+        cw.visit( JDK_VERSION, ACC_PUBLIC + ACC_SUPER, classSlash, null, baseClassSlash, new String[] { "org/apache/zest/api/composite/Composite" } );
 
         // Composite reference
         {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityInstance.java
index 3f55ba5..15c8524 100755
--- a/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityInstance.java
@@ -35,7 +35,6 @@ import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkException;
 import org.apache.zest.runtime.composite.CompositeMethodInstance;
 import org.apache.zest.runtime.composite.MixinsInstance;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
 import org.apache.zest.spi.entity.EntityState;
 import org.apache.zest.spi.entity.EntityStatus;
 import org.apache.zest.spi.module.ModuleSpi;
@@ -54,7 +53,7 @@ public final class EntityInstance
     }
 
     private final EntityComposite proxy;
-    private final ModuleUnitOfWork uow;
+    private final UnitOfWork uow;
     private final ModuleSpi moduleInstance;
     private final EntityModel entityModel;
     private final EntityReference identity;
@@ -63,7 +62,7 @@ public final class EntityInstance
     private Object[] mixins;
     private EntityStateInstance state;
 
-    public EntityInstance( ModuleUnitOfWork uow,
+    public EntityInstance( UnitOfWork uow,
                            ModuleSpi moduleInstance,
                            EntityModel entityModel,
                            EntityState entityState

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityModel.java
index 42b33b6..bac3936 100755
--- a/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityModel.java
@@ -31,7 +31,7 @@ import org.apache.zest.api.unitofwork.EntityCompositeAlreadyExistsException;
 import org.apache.zest.api.util.Annotations;
 import org.apache.zest.runtime.composite.CompositeMethodsModel;
 import org.apache.zest.runtime.composite.CompositeModel;
-import org.apache.zest.runtime.structure.ModuleUnitOfWork;
+import org.apache.zest.runtime.unitofwork.ModuleUnitOfWork;
 import org.apache.zest.spi.entity.EntityState;
 import org.apache.zest.spi.entitystore.EntityAlreadyExistsException;
 import org.apache.zest.spi.entitystore.EntityStoreException;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityStateInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityStateInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityStateInstance.java
index 0028c5a..c0a5cba 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityStateInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/entity/EntityStateInstance.java
@@ -62,14 +62,7 @@ public final class EntityStateInstance
         this.stateModel = stateModel;
         this.entityState = entityState;
 
-        entityFunction = new BiFunction<EntityReference, Type, Object>()
-        {
-            @Override
-            public Object apply( EntityReference entityReference, Type type )
-            {
-                return uow.get( Classes.RAW_CLASS.apply( type ), entityReference.identity() );
-            }
-        };
+        entityFunction = ( entityReference, type ) -> uow.get( Classes.RAW_CLASS.apply( type ), entityReference.identity() );
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/injection/InjectedFieldsModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/injection/InjectedFieldsModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/injection/InjectedFieldsModel.java
index 18126eb..ba9ac8d 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/injection/InjectedFieldsModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/injection/InjectedFieldsModel.java
@@ -57,23 +57,24 @@ public final class InjectedFieldsModel
         Type genericType = field.getGenericType();
         if( genericType instanceof ParameterizedType )
         {
-            genericType = new ParameterizedTypeInstance( ( (ParameterizedType) genericType ).getActualTypeArguments(), ( (ParameterizedType) genericType )
-                .getRawType(), ( (ParameterizedType) genericType ).getOwnerType() );
+            Type[] actualTypeArguments = ( (ParameterizedType) genericType ).getActualTypeArguments();
+            Type rawType = ( (ParameterizedType) genericType ).getRawType();
+            Type ownerType = ( (ParameterizedType) genericType ).getOwnerType();
+            genericType = new ParameterizedTypeInstance( actualTypeArguments, rawType, ownerType );
 
-            for( int i = 0; i < ( (ParameterizedType) genericType ).getActualTypeArguments().length; i++ )
+            for( int i = 0; i < actualTypeArguments.length; i++ )
             {
-                Type type = ( (ParameterizedType) genericType ).getActualTypeArguments()[ i ];
+                Type type = actualTypeArguments[ i ];
                 if( type instanceof TypeVariable )
                 {
                     type = Classes.resolveTypeVariable( (TypeVariable) type, field.getDeclaringClass(), fragmentClass );
-                    ( (ParameterizedType) genericType ).getActualTypeArguments()[ i ] = type;
+                    actualTypeArguments[ i ] = type;
                 }
             }
         }
 
         boolean optional = DependencyModel.isOptional( injectionAnnotation, field.getAnnotations() );
-        DependencyModel dependencyModel = new DependencyModel( injectionAnnotation, genericType, fragmentClass, optional, field
-            .getAnnotations() );
+        DependencyModel dependencyModel = new DependencyModel( injectionAnnotation, genericType, fragmentClass, optional, field.getAnnotations() );
         InjectedFieldModel injectedFieldModel = new InjectedFieldModel( field, dependencyModel );
         this.fields.add( injectedFieldModel );
     }
@@ -82,14 +83,6 @@ public final class InjectedFieldsModel
     public Stream<DependencyModel> dependencies()
     {
         return fields.stream().flatMap( Dependencies::dependencies );
-//        return Iterables.map( new Function<InjectedFieldModel, DependencyModel>()
-//        {
-//            @Override
-//            public DependencyModel apply( InjectedFieldModel injectedFieldModel )
-//            {
-//                return injectedFieldModel.dependency();
-//            }
-//        }, fields );
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/injection/provider/StructureInjectionProviderFactory.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/injection/provider/StructureInjectionProviderFactory.java b/core/runtime/src/main/java/org/apache/zest/runtime/injection/provider/StructureInjectionProviderFactory.java
index ad05b64..1fbb3a3 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/injection/provider/StructureInjectionProviderFactory.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/injection/provider/StructureInjectionProviderFactory.java
@@ -81,7 +81,7 @@ public final class StructureInjectionProviderFactory
             }
             else if( clazz.equals( UnitOfWorkFactory.class ) )
             {
-                return context.module();
+                return context.module().unitOfWorkFactory();
             }
             else if( clazz.equals( QueryBuilderFactory.class ) )
             {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/service/ServicesModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/service/ServicesModel.java b/core/runtime/src/main/java/org/apache/zest/runtime/service/ServicesModel.java
index 2fbfb32..4635d42 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/service/ServicesModel.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/service/ServicesModel.java
@@ -68,4 +68,16 @@ public class ServicesModel
     {
         return serviceModels.stream();
     }
+
+    public boolean contains( Class<?> type )
+    {
+        for( ServiceModel model : serviceModels )
+        {
+            if( model.hasType( type ) )
+            {
+                return true;
+            }
+        }
+        return false;
+    }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/core/runtime/src/main/java/org/apache/zest/runtime/structure/LayerInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/zest/runtime/structure/LayerInstance.java b/core/runtime/src/main/java/org/apache/zest/runtime/structure/LayerInstance.java
index 338f8cf..dec81c1 100644
--- a/core/runtime/src/main/java/org/apache/zest/runtime/structure/LayerInstance.java
+++ b/core/runtime/src/main/java/org/apache/zest/runtime/structure/LayerInstance.java
@@ -21,7 +21,6 @@ import org.apache.zest.api.activation.ActivationEventListener;
 import org.apache.zest.api.activation.ActivationException;
 import org.apache.zest.api.activation.PassivationException;
 import org.apache.zest.api.common.Visibility;
-import org.apache.zest.api.composite.ModelDescriptor;
 import org.apache.zest.api.composite.TransientDescriptor;
 import org.apache.zest.api.entity.EntityDescriptor;
 import org.apache.zest.api.object.ObjectDescriptor;
@@ -30,7 +29,7 @@ import org.apache.zest.api.structure.Layer;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.value.ValueDescriptor;
 import org.apache.zest.runtime.activation.ActivationDelegate;
-import org.apache.zest.spi.module.ModelModule;
+import org.apache.zest.spi.structure.ModelModule;
 
 /**
  * Instance of a Zest application layer. Contains a list of modules which are managed by this layer.


[3/9] zest-java git commit: ZEST-132, ZEST-97 UnitOfWorkFactory as a customizable Service UnitOfWork as a customizable Transient Class can be a Transient directly, with itself as both the Composite Type and the Mixin. SideEffects declarations

Posted by ni...@apache.org.
http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/restlet/requestreader/DefaultRequestReader.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/restlet/requestreader/DefaultRequestReader.java b/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/restlet/requestreader/DefaultRequestReader.java
index 6174483..fed3812 100644
--- a/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/restlet/requestreader/DefaultRequestReader.java
+++ b/libraries/rest-server/src/main/java/org/apache/zest/library/rest/server/restlet/requestreader/DefaultRequestReader.java
@@ -32,9 +32,10 @@ import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.property.PropertyDescriptor;
 import org.apache.zest.api.service.qualifier.Tagged;
-import org.apache.zest.api.structure.Module;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.util.Dates;
 import org.apache.zest.api.value.ValueBuilder;
+import org.apache.zest.api.value.ValueBuilderFactory;
 import org.apache.zest.api.value.ValueComposite;
 import org.apache.zest.api.value.ValueDeserializer;
 import org.apache.zest.api.value.ValueSerialization;
@@ -72,7 +73,10 @@ public class DefaultRequestReader
 {
     private static final Logger LOGGER = LoggerFactory.getLogger( DefaultRequestReader.class );
     @Structure
-    private Module module;
+    private UnitOfWorkFactory uowf;
+
+    @Structure
+    private ValueBuilderFactory vbf;
 
     @Service
     @Tagged( ValueSerialization.Formats.JSON )
@@ -187,7 +191,7 @@ public class DefaultRequestReader
                                                          "Bug in Restlet encountered; notify developers!" );
                         }
 
-                        Object command = module.newValueFromSerializedState( commandType, json );
+                        Object command = vbf.newValueFromSerializedState( commandType, json );
                         args[0] = command;
                         return args;
                     }
@@ -209,8 +213,7 @@ public class DefaultRequestReader
 
                         Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
                         Form entityAsForm;
-                        if( representation != null
-                            && !EmptyRepresentation.class.isInstance( representation )
+                        if( !EmptyRepresentation.class.isInstance( representation )
                             && representation.isAvailable() )
                         {
                             entityAsForm = new Form( representation );
@@ -234,8 +237,7 @@ public class DefaultRequestReader
                 {
                     Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
                     Form entityAsForm;
-                    if( representation != null
-                        && !EmptyRepresentation.class.isInstance( representation )
+                    if( !EmptyRepresentation.class.isInstance( representation )
                         && representation.isAvailable() )
                     {
                         entityAsForm = new Form( representation );
@@ -245,8 +247,8 @@ public class DefaultRequestReader
                         entityAsForm = new Form();
                     }
 
-                    args[0] = module.currentUnitOfWork().get( method.getParameterTypes()[0],
-                                                              getValue( "entity", queryAsForm, entityAsForm ) );
+                    args[0] = uowf.currentUnitOfWork().get( method.getParameterTypes()[0],
+                                                           getValue( "entity", queryAsForm, entityAsForm ) );
 
                     return args;
                 }
@@ -254,8 +256,7 @@ public class DefaultRequestReader
                 {
                     Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
                     Form entityAsForm;
-                    if( representation != null
-                        && !EmptyRepresentation.class.isInstance( representation )
+                    if( !EmptyRepresentation.class.isInstance( representation )
                         && representation.isAvailable() )
                     {
                         entityAsForm = new Form( representation );
@@ -278,13 +279,9 @@ public class DefaultRequestReader
                                              final Form entityAsForm
     )
     {
-        ValueBuilder<? extends ValueComposite> builder = module.newValueBuilderWithState(
+        ValueBuilder<? extends ValueComposite> builder = vbf.newValueBuilderWithState(
             valueType,
-            new Function<PropertyDescriptor, Object>()
-        {
-            @Override
-            public Object apply( PropertyDescriptor propertyDescriptor )
-            {
+            (Function<PropertyDescriptor, Object>) propertyDescriptor -> {
                 Parameter param = queryAsForm.getFirst( propertyDescriptor.qualifiedName().name() );
 
                 if( param == null )
@@ -309,39 +306,28 @@ public class DefaultRequestReader
                 }
 
                 return null;
-            }
             },
-            new Function<AssociationDescriptor, EntityReference>()
-            {
-                @Override
-                public EntityReference apply( AssociationDescriptor associationDescriptor )
-                {
-                    Parameter param = queryAsForm.getFirst( associationDescriptor.qualifiedName().name() );
+            (Function<AssociationDescriptor, EntityReference>) associationDescriptor -> {
+                Parameter param = queryAsForm.getFirst( associationDescriptor.qualifiedName().name() );
 
-                    if( param == null )
-                    {
-                        param = entityAsForm.getFirst( associationDescriptor.qualifiedName().name() );
-                    }
+                if( param == null )
+                {
+                    param = entityAsForm.getFirst( associationDescriptor.qualifiedName().name() );
+                }
 
-                    if( param != null )
-                    {
-                        return EntityReference.parseEntityReference( param.getValue() );
-                    }
-                    else
-                    {
-                        return null;
-                    }
+                if( param != null )
+                {
+                    return EntityReference.parseEntityReference( param.getValue() );
                 }
-            },
-            new Function<AssociationDescriptor, Iterable<EntityReference>>()
-            {
-                @Override
-                public Iterable<EntityReference> apply( AssociationDescriptor associationDescriptor )
+                else
                 {
-                    // TODO
-                    return Iterables.empty();
+                    return null;
                 }
             },
+            (Function<AssociationDescriptor, Iterable<EntityReference>>) associationDescriptor -> {
+                // TODO
+                return Iterables.empty();
+            },
             new Function<AssociationDescriptor, Map<String, EntityReference>>()
             {
                 @Override
@@ -470,7 +456,7 @@ public class DefaultRequestReader
             }
             else if( parameterType.isInterface() )
             {
-                arg = module.currentUnitOfWork().get( parameterType, argString );
+                arg = uowf.currentUnitOfWork().get( parameterType, argString );
             }
             else
             {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest/src/main/java/org/apache/zest/library/rest/admin/RestApplication.java
----------------------------------------------------------------------
diff --git a/libraries/rest/src/main/java/org/apache/zest/library/rest/admin/RestApplication.java b/libraries/rest/src/main/java/org/apache/zest/library/rest/admin/RestApplication.java
index aa28069..206c71f 100644
--- a/libraries/rest/src/main/java/org/apache/zest/library/rest/admin/RestApplication.java
+++ b/libraries/rest/src/main/java/org/apache/zest/library/rest/admin/RestApplication.java
@@ -19,9 +19,17 @@ package org.apache.zest.library.rest.admin;
 
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
-import org.apache.zest.api.structure.Module;
-import org.apache.zest.api.unitofwork.*;
-import org.restlet.*;
+import org.apache.zest.api.object.ObjectFactory;
+import org.apache.zest.api.unitofwork.ConcurrentEntityModificationException;
+import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
+import org.restlet.Application;
+import org.restlet.Context;
+import org.restlet.Request;
+import org.restlet.Response;
+import org.restlet.Restlet;
 import org.restlet.data.MediaType;
 import org.restlet.data.Status;
 import org.restlet.resource.Finder;
@@ -34,7 +42,10 @@ public class RestApplication
     public static final MediaType APPLICATION_SPARQL_JSON = new MediaType( "application/sparql-results+json", "SPARQL JSON" );
 
     @Structure
-    private Module module;
+    private ObjectFactory objectFactory;
+
+    @Structure
+    private UnitOfWorkFactory uowf;
 
     public RestApplication( @Uses Context parentContext )
     {
@@ -48,7 +59,7 @@ public class RestApplication
     @Override
     public void handle( Request request, Response response )
     {
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             super.handle( request, response );
@@ -96,7 +107,7 @@ public class RestApplication
 
     private Finder newFinder( Class<? extends ServerResource> resource )
     {
-        Finder finder = module.newObject( Finder.class );
+        Finder finder = objectFactory.newObject( Finder.class );
         finder.setTargetClass( resource );
         return finder;
     }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/rest/src/test/java/org/apache/zest/library/rest/admin/RestTest.java
----------------------------------------------------------------------
diff --git a/libraries/rest/src/test/java/org/apache/zest/library/rest/admin/RestTest.java b/libraries/rest/src/test/java/org/apache/zest/library/rest/admin/RestTest.java
index 543ecf3..bb75c84 100644
--- a/libraries/rest/src/test/java/org/apache/zest/library/rest/admin/RestTest.java
+++ b/libraries/rest/src/test/java/org/apache/zest/library/rest/admin/RestTest.java
@@ -27,8 +27,6 @@ import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.methods.DeleteMethod;
 import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.commons.httpclient.methods.PostMethod;
-import org.junit.Before;
-import org.junit.Test;
 import org.apache.zest.api.association.Association;
 import org.apache.zest.api.common.Optional;
 import org.apache.zest.api.entity.EntityBuilder;
@@ -42,14 +40,19 @@ import org.apache.zest.bootstrap.ApplicationAssemblerAdapter;
 import org.apache.zest.bootstrap.Assembler;
 import org.apache.zest.bootstrap.AssemblyException;
 import org.apache.zest.bootstrap.ModuleAssembly;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.apache.zest.entitystore.memory.MemoryEntityStoreService;
 import org.apache.zest.index.rdf.assembly.RdfMemoryStoreAssembler;
 import org.apache.zest.spi.uuid.UuidIdentityGeneratorService;
 import org.apache.zest.test.AbstractZestTest;
+import org.junit.Before;
+import org.junit.Test;
 
 import static org.hamcrest.CoreMatchers.anyOf;
 import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
 
 public class RestTest
     extends AbstractZestTest
@@ -59,18 +62,20 @@ public class RestTest
     protected ApplicationDescriptor newApplication()
         throws AssemblyException
     {
-        return zest.newApplicationModel( new ApplicationAssemblerAdapter( new Assembler[][][]
-            {
+        return zest.newApplicationModel( new ApplicationAssemblerAdapter(
+            new Assembler[][][]
                 {
                     {
-                        RestTest.this,
-                        new RestAssembler(),
-                        new RdfMemoryStoreAssembler()
+                        {
+                            RestTest.this,
+                            new RestAssembler(),
+                            new RdfMemoryStoreAssembler(),
+                            new DefaultUnitOfWorkAssembler()
+                        }
                     }
-                }
-            } )
-        {
-        } );
+                } )
+        {}  // subclassing ApplicationAssemblerAdapter
+        );
     }
 
     @Override
@@ -90,7 +95,7 @@ public class RestTest
         throws Exception
     {
         super.setUp();
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
         try
         {
             EntityBuilder<PersonEntity> builder1 = uow.newEntityBuilder( PersonEntity.class, "P2" );
@@ -141,7 +146,7 @@ public class RestTest
         properties.put( "firstname", "Jack" );
         properties.put( "lastname", "Doe" );
         restTester.putEntity( "P1", properties );
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         try
         {
             PersonEntity entity = work.get( PersonEntity.class, "P1" );
@@ -161,7 +166,7 @@ public class RestTest
     {
         RestTester restTester = module.newObject( RestTester.class );
         restTester.deleteEntity( "P1" );
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         try
         {
             PersonEntity entity = null;
@@ -191,10 +196,10 @@ public class RestTest
         assertThat(
             "Returned RDF", result,
             anyOf(
-            equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n</rdf:RDF>\n" ),
-            equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\\\"no\\\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n</rdf:RDF>\n" ),
-            equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n</rdf:RDF>\n" ),
-            equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\\\"no\\\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n</rdf:RDF>\n" ) ) );
+                equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n</rdf:RDF>\n" ),
+                equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\\\"no\\\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n</rdf:RDF>\n" ),
+                equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n</rdf:RDF>\n" ),
+                equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\\\"no\\\"?>\n<rdf:RDF\n\txmlns=\"urn:zest:\"\n\txmlns:zest=\"http://zest.apache.org/rdf/model/1.0/\"\n\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n<zest:entity rdf:about=\"/entity/P1.rdf\"/>\n<zest:entity rdf:about=\"/entity/P2.rdf\"/>\n</rdf:RDF>\n" ) ) );
     }
 
     public static class RestTester
@@ -214,7 +219,8 @@ public class RestTest
                 int status = client.executeMethod( method );
                 if( status != 200 )
                 {
-                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method.getStatusText() + "'" );
+                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method
+                        .getStatusText() + "'" );
                 }
                 InputStream input = method.getResponseBodyAsStream();
                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -241,7 +247,8 @@ public class RestTest
                 int status = client.executeMethod( method );
                 if( status != 205 )
                 {
-                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method.getStatusText() + "'" );
+                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method
+                        .getStatusText() + "'" );
                 }
             }
             finally
@@ -260,7 +267,8 @@ public class RestTest
                 int status = client.executeMethod( method );
                 if( status != 204 )
                 {
-                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method.getStatusText() + "'" );
+                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method
+                        .getStatusText() + "'" );
                 }
             }
             finally
@@ -280,7 +288,8 @@ public class RestTest
                 int status = client.executeMethod( method );
                 if( status != 200 )
                 {
-                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method.getStatusText() + "'" );
+                    throw new RuntimeException( "EntityResource returned status code: '" + status + "' and message: '" + method
+                        .getStatusText() + "'" );
                 }
                 InputStream input = method.getResponseBodyAsStream();
                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -320,5 +329,4 @@ public class RestTest
         @Optional
         Association<Person> mother();
     }
-
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/Scheduler.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/Scheduler.java b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/Scheduler.java
index 8510645..87e0963 100644
--- a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/Scheduler.java
+++ b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/Scheduler.java
@@ -48,9 +48,6 @@ import static org.apache.zest.api.unitofwork.concern.UnitOfWorkPropagation.Propa
  * any ordinary {@link org.apache.zest.api.entity.EntityComposite}. There is also a {@link Schedules}
  * entity composite that has Associations to all active, completed and cancelled schedules.
  * </p>
- * <p>
- *
- * </p>
  */
 @Concerns( UnitOfWorkConcern.class )
 public interface Scheduler

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/SchedulesHandler.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/SchedulesHandler.java b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/SchedulesHandler.java
index b4a2b4d..4708239 100644
--- a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/SchedulesHandler.java
+++ b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/SchedulesHandler.java
@@ -24,19 +24,19 @@ import org.apache.zest.api.entity.Identity;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.mixin.Mixins;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.unitofwork.concern.UnitOfWorkPropagation;
 import org.apache.zest.library.scheduler.internal.Schedules;
 
-@Mixins(SchedulesHandler.SchedulesHandlerMixin.class)
+@Mixins( SchedulesHandler.SchedulesHandlerMixin.class )
 public interface SchedulesHandler
 {
-    @UnitOfWorkPropagation( UnitOfWorkPropagation.Propagation.MANDATORY)
+    @UnitOfWorkPropagation( UnitOfWorkPropagation.Propagation.MANDATORY )
     Schedules getActiveSchedules();
 
-    @UnitOfWorkPropagation( UnitOfWorkPropagation.Propagation.MANDATORY)
+    @UnitOfWorkPropagation( UnitOfWorkPropagation.Propagation.MANDATORY )
     Schedules getCancelledSchedules();
 
     class SchedulesHandlerMixin implements SchedulesHandler
@@ -45,18 +45,18 @@ public interface SchedulesHandler
         private Identity me;
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory module;
 
         @Override
         public Schedules getActiveSchedules()
         {
-            return getOrCreateSchedules(getActiveSchedulesIdentity());
+            return getOrCreateSchedules( getActiveSchedulesIdentity() );
         }
 
         @Override
         public Schedules getCancelledSchedules()
         {
-            return getOrCreateSchedules(getCancelledSchedulesIdentity());
+            return getOrCreateSchedules( getCancelledSchedulesIdentity() );
         }
 
         public String getActiveSchedulesIdentity()
@@ -69,7 +69,8 @@ public interface SchedulesHandler
             return "Schedules-Cancelled:" + me.identity().get();
         }
 
-        private Schedules getOrCreateSchedules( String identity ){
+        private Schedules getOrCreateSchedules( String identity )
+        {
             UnitOfWork uow = module.currentUnitOfWork();
             Schedules schedules;
             try
@@ -82,8 +83,6 @@ public interface SchedulesHandler
                 schedules = uow.newEntity( Schedules.class, identity );
             }
             return schedules;
-
         }
-
     }
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/defaults/DefaultScheduleFactoryMixin.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/defaults/DefaultScheduleFactoryMixin.java b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/defaults/DefaultScheduleFactoryMixin.java
index 27c7125..3eb93b4 100644
--- a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/defaults/DefaultScheduleFactoryMixin.java
+++ b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/defaults/DefaultScheduleFactoryMixin.java
@@ -23,14 +23,14 @@ package org.apache.zest.library.scheduler.defaults;
 import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
-import org.apache.zest.library.scheduler.SchedulerService;
-import org.apache.zest.library.scheduler.Task;
-import org.apache.zest.library.scheduler.Schedule;
-import org.apache.zest.library.scheduler.ScheduleFactory;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.scheduler.CronSchedule;
 import org.apache.zest.library.scheduler.OnceSchedule;
+import org.apache.zest.library.scheduler.Schedule;
+import org.apache.zest.library.scheduler.ScheduleFactory;
+import org.apache.zest.library.scheduler.SchedulerService;
+import org.apache.zest.library.scheduler.Task;
 import org.apache.zest.spi.uuid.UuidIdentityGeneratorService;
 import org.joda.time.DateTime;
 import org.slf4j.Logger;
@@ -42,7 +42,7 @@ public class DefaultScheduleFactoryMixin
     private static final Logger logger = LoggerFactory.getLogger( ScheduleFactory.class );
 
     @Structure
-    private Module module;
+    private UnitOfWorkFactory uowf;
 
     @Service
     private SchedulerService scheduler;
@@ -64,7 +64,7 @@ public class DefaultScheduleFactoryMixin
 
     private CronSchedule newPersistentCronSchedule( Task task, String cronExpression, DateTime start )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<CronSchedule> builder = uow.newEntityBuilder( CronSchedule.class );
         CronSchedule instance = builder.instance();
         instance.task().set( task );
@@ -78,7 +78,7 @@ public class DefaultScheduleFactoryMixin
 
     private Schedule newPersistentOnceSchedule( Task task, DateTime runAt )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         EntityBuilder<OnceSchedule> builder = uow.newEntityBuilder( OnceSchedule.class );
         OnceSchedule builderInstance = builder.instance();
         builderInstance.task().set( task );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/Execution.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/Execution.java b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/Execution.java
index 1925ac6..e3b9312 100644
--- a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/Execution.java
+++ b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/Execution.java
@@ -27,15 +27,14 @@ import java.util.concurrent.RejectedExecutionHandler;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
-import org.apache.zest.api.concern.Concerns;
+import org.apache.zest.api.composite.TransientBuilderFactory;
 import org.apache.zest.api.configuration.Configuration;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.mixin.Mixins;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
-import org.apache.zest.api.unitofwork.concern.UnitOfWorkConcern;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.scheduler.Schedule;
 import org.apache.zest.library.scheduler.Scheduler;
 import org.apache.zest.library.scheduler.SchedulerConfiguration;
@@ -66,7 +65,10 @@ public interface Execution
         private final Object lock = new Object();
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
+
+        @Structure
+        private TransientBuilderFactory tbf;
 
         @This
         private Scheduler scheduler;
@@ -164,7 +166,7 @@ public interface Execution
         {
             long now = System.currentTimeMillis();
 
-            try (UnitOfWork uow = module.newUnitOfWork()) // This will discard() the UoW when block is exited. We are only doing reads, so fine.
+            try (UnitOfWork uow = uowf.newUnitOfWork()) // This will discard() the UoW when block is exited. We are only doing reads, so fine.
             {
                 submitTaskForExecution( oldScheduleTime );
                 Schedule schedule = uow.get( Schedule.class, oldScheduleTime.scheduleIdentity() );
@@ -196,7 +198,7 @@ public interface Execution
 
         private void submitTaskForExecution( ScheduleTime scheduleTime )
         {
-            Runnable taskRunner = module.newTransient( Runnable.class, scheduleTime );
+            Runnable taskRunner = tbf.newTransient( Runnable.class, scheduleTime );
             this.taskExecutor.submit( taskRunner );
         }
 

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/SchedulerMixin.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/SchedulerMixin.java b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/SchedulerMixin.java
index 4f2272b..75212fe 100644
--- a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/SchedulerMixin.java
+++ b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/SchedulerMixin.java
@@ -24,10 +24,10 @@ import org.apache.zest.api.injection.scope.Service;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.service.ServiceActivation;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.UsecaseBuilder;
 import org.apache.zest.library.scheduler.Scheduler;
 import org.apache.zest.library.scheduler.SchedulerConfiguration;
@@ -50,7 +50,7 @@ public class SchedulerMixin
     private ScheduleFactory scheduleFactory;
 
     @Structure
-    private Module module;
+    private UnitOfWorkFactory uowf;
 
     @This
     private SchedulerService me;
@@ -120,7 +120,7 @@ public class SchedulerMixin
     @Override
     public void cancelSchedule( String scheduleId )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         Schedule schedule;
         try
         {
@@ -153,7 +153,7 @@ public class SchedulerMixin
     private void loadSchedules()
         throws UnitOfWorkCompletionException
     {
-        try (UnitOfWork ignored = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Initialize Schedules" ) ))
+        try (UnitOfWork ignored = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Initialize Schedules" ) ))
         {
             Schedules schedules = schedulesHandler.getActiveSchedules();
             for( Schedule schedule : schedules.schedules() )

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/TaskRunner.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/TaskRunner.java b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/TaskRunner.java
index fa52d73..fd88d9a 100644
--- a/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/TaskRunner.java
+++ b/libraries/scheduler/src/main/java/org/apache/zest/library/scheduler/internal/TaskRunner.java
@@ -24,11 +24,11 @@ import java.lang.reflect.UndeclaredThrowableException;
 import java.util.concurrent.locks.ReentrantLock;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.Uses;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.UsecaseBuilder;
-import org.apache.zest.library.scheduler.Task;
 import org.apache.zest.library.scheduler.Schedule;
+import org.apache.zest.library.scheduler.Task;
 
 public class TaskRunner
     implements Runnable
@@ -36,7 +36,7 @@ public class TaskRunner
     private static ReentrantLock lock = new ReentrantLock();
 
     @Structure
-    private Module module;
+    private UnitOfWorkFactory uowf;
 
     @Uses
     private ScheduleTime schedule;
@@ -45,7 +45,7 @@ public class TaskRunner
     public void run()
     {
         // TODO: (niclas) I am NOT happy with this implementation, requiring 3 UnitOfWorks to be created. 15-20 milliseconds on my MacBook. If there is a better way to detect overrun, two of those might not be needed.
-        UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Task Runner initialize" ) );
+        UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Task Runner initialize" ) );
         try
         {
             lock.lock();
@@ -58,14 +58,14 @@ public class TaskRunner
                     schedule.running().set( true );
                     uow.complete();                     // This completion is needed to detect overrun
 
-                    uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Task Runner" ) );
+                    uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Task Runner" ) );
                     schedule = uow.get( schedule );     // re-attach the entity to the new UnitOfWork
                     Task task = schedule.task().get();
                     lock.unlock();
                     task.run();
                     lock.lock();
                     uow.complete();
-                    uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Task Runner conclude" ) );
+                    uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Task Runner conclude" ) );
                     schedule = uow.get( schedule );     // re-attach the entity to the new UnitOfWork
                     schedule.running().set( false );
                     schedule.taskCompletedSuccessfully();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/CronScheduleTest.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/CronScheduleTest.java b/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/CronScheduleTest.java
index ed999fd..8b7dff9 100644
--- a/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/CronScheduleTest.java
+++ b/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/CronScheduleTest.java
@@ -48,7 +48,7 @@ public class CronScheduleTest extends AbstractZestTest
         throws Exception
     {
 
-        UnitOfWork work = module.newUnitOfWork();
+        UnitOfWork work = uowf.newUnitOfWork();
         EntityBuilder<Task> builder1 = work.newEntityBuilder( Task.class );
         builder1.instance().name().set( "abc" );
         Task task = builder1.newInstance();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/SchedulerTest.java
----------------------------------------------------------------------
diff --git a/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/SchedulerTest.java b/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/SchedulerTest.java
index 15a356c..f2c8fc6 100644
--- a/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/SchedulerTest.java
+++ b/libraries/scheduler/src/test/java/org/apache/zest/library/scheduler/SchedulerTest.java
@@ -73,14 +73,14 @@ public class SchedulerTest
     {
         Usecase usecase = UsecaseBuilder.newUsecase( "testTask" );
         String taskId;
-        try( UnitOfWork uow = module.newUnitOfWork( usecase ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( usecase ) )
         {
             FooTask task = createFooTask( uow, "TestTask", BAZAR );
             taskId = task.identity().get();
             task.run();
             uow.complete();
         }
-        try( UnitOfWork uow = module.newUnitOfWork( usecase ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( usecase ) )
         {
             FooTask task = uow.get( FooTask.class, taskId );
             assertThat( task.runCounter().get(), equalTo( 1 ) );
@@ -96,7 +96,7 @@ public class SchedulerTest
         DateTime start = new DateTime();
         String taskIdentity;
         long sleepMillis;
-        try( UnitOfWork uow = module.newUnitOfWork( usecase ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( usecase ) )
         {
             Scheduler scheduler = module.findService( Scheduler.class ).get();
 
@@ -117,7 +117,7 @@ public class SchedulerTest
             .until( taskOutput( taskIdentity ), equalTo( 1 ) );
 
         //noinspection unused
-        try( UnitOfWork uow = module.newUnitOfWork( usecase ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( usecase ) )
         {
             Timeline timeline = module.findService( Timeline.class ).get();
             DateTime now = new DateTime();
@@ -153,7 +153,7 @@ public class SchedulerTest
         Schedule schedule2;
         Schedule schedule3;
         Schedule schedule4;
-        try( UnitOfWork uow = module.newUnitOfWork( usecase ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( usecase ) )
         {
             FooTask task = createFooTask( uow, usecase.name(), BAZAR );
             taskIdentity = task.identity().get();
@@ -169,7 +169,7 @@ public class SchedulerTest
             .atMost( 6, SECONDS )
             .until( taskOutput( taskIdentity ), equalTo( 4 ) );
 
-        try( UnitOfWork uow = module.newUnitOfWork( usecase ) )
+        try( UnitOfWork uow = uowf.newUnitOfWork( usecase ) )
         {
             schedule1 = uow.get( schedule1 );
             schedule2 = uow.get( schedule2 );
@@ -193,7 +193,7 @@ public class SchedulerTest
     private Callable<Integer> taskOutput( final String taskIdentity )
     {
         return () -> {
-            try( UnitOfWork uow = module.newUnitOfWork() )
+            try( UnitOfWork uow = uowf.newUnitOfWork() )
             {
                 FooTask task = uow.get( FooTask.class, taskIdentity );
                 Integer count = task.runCounter().get();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/passwords/PasswordRealmMixin.java
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/passwords/PasswordRealmMixin.java b/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/passwords/PasswordRealmMixin.java
index 2b26353..6e52b7d 100644
--- a/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/passwords/PasswordRealmMixin.java
+++ b/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/passwords/PasswordRealmMixin.java
@@ -33,9 +33,10 @@ import org.apache.zest.api.configuration.Configuration;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.query.QueryBuilder;
+import org.apache.zest.api.query.QueryBuilderFactory;
 import org.apache.zest.api.service.ServiceActivation;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.shiro.Shiro;
 import org.apache.zest.library.shiro.domain.permissions.RoleAssignee;
 import org.slf4j.Logger;
@@ -45,14 +46,17 @@ import static org.apache.zest.api.query.QueryExpressions.eq;
 import static org.apache.zest.api.query.QueryExpressions.templateFor;
 
 public class PasswordRealmMixin
-        extends AuthorizingRealm
-        implements Realm, Authorizer, PasswordService, ServiceActivation
+    extends AuthorizingRealm
+    implements Realm, Authorizer, PasswordService, ServiceActivation
 {
 
     private static final Logger LOG = LoggerFactory.getLogger( Shiro.LOGGER_NAME );
 
     @Structure
-    private Module module;
+    private UnitOfWorkFactory uowf;
+
+    @Structure
+    private QueryBuilderFactory qbf;
 
     @This
     private Configuration<PasswordRealmConfiguration> configuration;
@@ -70,18 +74,21 @@ public class PasswordRealmMixin
 
     @Override
     public void activateService()
-            throws Exception
+        throws Exception
     {
         configuration.refresh();
         PasswordRealmConfiguration config = configuration.get();
         String algorithm = config.hashAlgorithmName().get();
         Integer iterations = config.hashIterationsCount().get();
-        if ( algorithm != null || iterations != null ) {
-            DefaultHashService hashService = ( DefaultHashService ) passwordService.getHashService();
-            if ( algorithm != null ) {
+        if( algorithm != null || iterations != null )
+        {
+            DefaultHashService hashService = (DefaultHashService) passwordService.getHashService();
+            if( algorithm != null )
+            {
                 hashService.setHashAlgorithmName( algorithm );
             }
-            if ( iterations != null ) {
+            if( iterations != null )
+            {
                 hashService.setHashIterations( iterations );
             }
         }
@@ -89,13 +96,13 @@ public class PasswordRealmMixin
 
     @Override
     public void passivateService()
-            throws Exception
+        throws Exception
     {
     }
 
     @Override
     public String encryptPassword( Object plaintextPassword )
-            throws IllegalArgumentException
+        throws IllegalArgumentException
     {
         return passwordService.encryptPassword( plaintextPassword );
     }
@@ -108,21 +115,25 @@ public class PasswordRealmMixin
 
     @Override
     protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token )
-            throws AuthenticationException
+        throws AuthenticationException
     {
-        UnitOfWork uow = module.newUnitOfWork();
-        try {
+        UnitOfWork uow = uowf.newUnitOfWork();
+        try
+        {
 
-            String username = ( ( UsernamePasswordToken ) token ).getUsername();
+            String username = ( (UsernamePasswordToken) token ).getUsername();
             PasswordSecurable account = findPasswordSecurable( uow, username );
-            if ( account == null ) {
+            if( account == null )
+            {
                 LOG.debug( "Unknown subject identifier: {}" + username );
                 return null;
             }
             LOG.debug( "Found account for {}: {}", username, account );
-            return new SimpleAuthenticationInfo( account.subjectIdentifier().get(), account.password().get(), getName() );
-
-        } finally {
+            return new SimpleAuthenticationInfo( account.subjectIdentifier().get(), account.password()
+                .get(), getName() );
+        }
+        finally
+        {
             uow.discard();
         }
     }
@@ -130,12 +141,14 @@ public class PasswordRealmMixin
     @Override
     protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals )
     {
-        UnitOfWork uow = module.newUnitOfWork();
-        try {
+        UnitOfWork uow = uowf.newUnitOfWork();
+        try
+        {
 
             String username = getAvailablePrincipal( principals ).toString();
             RoleAssignee roleAssignee = findRoleAssignee( uow, username );
-            if ( roleAssignee == null ) {
+            if( roleAssignee == null )
+            {
                 LOG.debug( "No authorization info for {}", username );
                 return null;
             }
@@ -147,24 +160,24 @@ public class PasswordRealmMixin
             SimpleAuthorizationInfo atzInfo = new SimpleAuthorizationInfo( roleNames );
             atzInfo.setStringPermissions( permissionStrings );
             return atzInfo;
-
-        } finally {
+        }
+        finally
+        {
             uow.discard();
         }
     }
 
     private PasswordSecurable findPasswordSecurable( UnitOfWork uow, String username )
     {
-        QueryBuilder<PasswordSecurable> builder = module.newQueryBuilder( PasswordSecurable.class );
+        QueryBuilder<PasswordSecurable> builder = qbf.newQueryBuilder( PasswordSecurable.class );
         builder = builder.where( eq( templateFor( PasswordSecurable.class ).subjectIdentifier(), username ) );
         return uow.newQuery( builder ).find();
     }
 
     private RoleAssignee findRoleAssignee( UnitOfWork uow, String username )
     {
-        QueryBuilder<RoleAssignee> builder = module.newQueryBuilder( RoleAssignee.class );
+        QueryBuilder<RoleAssignee> builder = qbf.newQueryBuilder( RoleAssignee.class );
         builder = builder.where( eq( templateFor( RoleAssignee.class ).subjectIdentifier(), username ) );
         return uow.newQuery( builder ).find();
     }
-
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/Role.java
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/Role.java b/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/Role.java
index f8fc925..e4c0282 100644
--- a/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/Role.java
+++ b/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/Role.java
@@ -21,8 +21,8 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.property.Property;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 
 @Mixins( Role.Mixin.class )
 public interface Role
@@ -41,7 +41,7 @@ public interface Role
     {
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @This
         private Role role;
@@ -49,7 +49,7 @@ public interface Role
         @Override
         public RoleAssignment assignTo( RoleAssignee assignee )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             EntityBuilder<RoleAssignment> builder = uow.newEntityBuilder( RoleAssignment.class );
             RoleAssignment assignment = builder.instance();
             assignment.assignee().set( assignee );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/RoleFactory.java
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/RoleFactory.java b/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/RoleFactory.java
index 87f6b68..4b5b555 100644
--- a/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/RoleFactory.java
+++ b/libraries/shiro-core/src/main/java/org/apache/zest/library/shiro/domain/permissions/RoleFactory.java
@@ -23,8 +23,8 @@ import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceComposite;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.functional.Iterables;
 
 @Mixins( RoleFactory.Mixin.class )
@@ -41,7 +41,7 @@ public interface RoleFactory
     {
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Override
         public Role create( String name, String... permissions )
@@ -52,7 +52,7 @@ public interface RoleFactory
         @Override
         public Role create( String name, Iterable<String> permissions )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = uowf.currentUnitOfWork();
             EntityBuilder<Role> roleBuilder = uow.newEntityBuilder( Role.class );
             Role role = roleBuilder.instance();
             role.name().set( name );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PasswordDomainTest.java
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PasswordDomainTest.java b/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PasswordDomainTest.java
index 90f9d87..35a9ceb 100644
--- a/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PasswordDomainTest.java
+++ b/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PasswordDomainTest.java
@@ -17,6 +17,7 @@ import org.apache.shiro.SecurityUtils;
 import org.apache.shiro.authc.UsernamePasswordToken;
 import org.apache.shiro.authc.credential.PasswordService;
 import org.apache.shiro.subject.Subject;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Test;
 import org.apache.zest.api.common.Visibility;
 import org.apache.zest.api.entity.EntityBuilder;
@@ -65,7 +66,7 @@ public class PasswordDomainTest
     {
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Service
         private PasswordService passwordService;
@@ -73,7 +74,7 @@ public class PasswordDomainTest
         @Override
         public User createNewUser( String username, String password )
         {
-            EntityBuilder<User> userBuilder = module.currentUnitOfWork().newEntityBuilder( User.class );
+            EntityBuilder<User> userBuilder = uowf.currentUnitOfWork().newEntityBuilder( User.class );
             User user = userBuilder.instance();
             user.subjectIdentifier().set( username );
             user.password().set( passwordService.encryptPassword( password ) );
@@ -116,7 +117,7 @@ public class PasswordDomainTest
             throws UnitOfWorkCompletionException
     {
 
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         UserFactory userFactory = module.findService( UserFactory.class ).get();
         // START SNIPPET: usage
@@ -125,7 +126,7 @@ public class PasswordDomainTest
         // END SNIPPET: usage
         uow.complete();
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
 
         // START SNIPPET: usage
         Subject currentUser = SecurityUtils.getSubject();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PermissionsDomainTest.java
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PermissionsDomainTest.java b/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PermissionsDomainTest.java
index 8fcb885..a436896 100644
--- a/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PermissionsDomainTest.java
+++ b/libraries/shiro-core/src/test/java/org/apache/zest/library/shiro/PermissionsDomainTest.java
@@ -17,6 +17,7 @@ import org.apache.shiro.SecurityUtils;
 import org.apache.shiro.authc.UsernamePasswordToken;
 import org.apache.shiro.authc.credential.PasswordService;
 import org.apache.shiro.subject.Subject;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.common.Visibility;
@@ -69,7 +70,7 @@ public class PermissionsDomainTest
     {
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Service
         private PasswordService passwordService;
@@ -77,7 +78,7 @@ public class PermissionsDomainTest
         @Override
         public User createNewUser( String username, String password )
         {
-            EntityBuilder<User> userBuilder = module.currentUnitOfWork().newEntityBuilder( User.class );
+            EntityBuilder<User> userBuilder = uowf.currentUnitOfWork().newEntityBuilder( User.class );
             User user = userBuilder.instance();
             user.subjectIdentifier().set( username );
             user.password().set( passwordService.encryptPassword( password ) );
@@ -129,7 +130,7 @@ public class PermissionsDomainTest
             throws UnitOfWorkCompletionException
     {
         // START SNIPPET: usage
-        UnitOfWork uow = module.newUnitOfWork();
+        UnitOfWork uow = uowf.newUnitOfWork();
 
         User user = userFactory.createNewUser( "foo", "bar" );
         Role role = roleFactory.create( "role-one", "permission-one", "permission-two" );
@@ -139,7 +140,7 @@ public class PermissionsDomainTest
 
         // END SNIPPET: usage
         // START SNIPPET: usage
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
 
         Subject currentUser = SecurityUtils.getSubject();
         currentUser.login( new UsernamePasswordToken( "foo", "bar" ) );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/sql-liquibase/src/test/java/org/apache/zest/library/sql/liquibase/LiquibaseServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/src/test/java/org/apache/zest/library/sql/liquibase/LiquibaseServiceTest.java b/libraries/sql-liquibase/src/test/java/org/apache/zest/library/sql/liquibase/LiquibaseServiceTest.java
index e3202de..8555f14 100644
--- a/libraries/sql-liquibase/src/test/java/org/apache/zest/library/sql/liquibase/LiquibaseServiceTest.java
+++ b/libraries/sql-liquibase/src/test/java/org/apache/zest/library/sql/liquibase/LiquibaseServiceTest.java
@@ -21,6 +21,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.function.Function;
 import javax.sql.DataSource;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationEvent;
 import org.apache.zest.api.activation.ActivationEventListener;
@@ -86,6 +87,8 @@ public class LiquibaseServiceTest
                 // END SNIPPET: assembly
                 module.forMixin( LiquibaseConfiguration.class ).declareDefaults().enabled().set( true );
                 module.forMixin( LiquibaseConfiguration.class ).declareDefaults().changeLog().set( "changelog.xml" );
+
+                new DefaultUnitOfWorkAssembler().assemble( module );
             }
 
             @Override

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/sql/src/main/java/org/apache/zest/library/sql/datasource/AbstractDataSourceServiceImporterMixin.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/main/java/org/apache/zest/library/sql/datasource/AbstractDataSourceServiceImporterMixin.java b/libraries/sql/src/main/java/org/apache/zest/library/sql/datasource/AbstractDataSourceServiceImporterMixin.java
index 5774fd4..93fa811 100644
--- a/libraries/sql/src/main/java/org/apache/zest/library/sql/datasource/AbstractDataSourceServiceImporterMixin.java
+++ b/libraries/sql/src/main/java/org/apache/zest/library/sql/datasource/AbstractDataSourceServiceImporterMixin.java
@@ -27,10 +27,10 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.service.ImportedServiceDescriptor;
 import org.apache.zest.api.service.ServiceImporter;
 import org.apache.zest.api.service.ServiceImporterException;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.NoSuchEntityException;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.usecase.UsecaseBuilder;
 import org.apache.zest.library.circuitbreaker.CircuitBreaker;
 import org.apache.zest.library.conversion.values.EntityToValue;
@@ -43,14 +43,14 @@ public abstract class AbstractDataSourceServiceImporterMixin<PooledDataSourceTyp
 
     protected static final Logger LOGGER = LoggerFactory.getLogger( AbstractDataSourceServiceImporterMixin.class );
 
-    private final Map<String, DataSourceConfigurationValue> configs = new HashMap<String, DataSourceConfigurationValue>();
+    private final Map<String, DataSourceConfigurationValue> configs = new HashMap<>();
 
-    private final Map<String, PooledDataSourceType> pools = new HashMap<String, PooledDataSourceType>();
+    private final Map<String, PooledDataSourceType> pools = new HashMap<>();
 
-    private final Map<DataSource, CircuitBreaker> circuitBreakers = new HashMap<DataSource, CircuitBreaker>();
+    private final Map<DataSource, CircuitBreaker> circuitBreakers = new HashMap<>();
 
     @Structure
-    protected Module module;
+    protected UnitOfWorkFactory uowf;
 
     @Service
     private EntityToValue entityToValue;
@@ -126,7 +126,7 @@ public abstract class AbstractDataSourceServiceImporterMixin<PooledDataSourceTyp
     {
         DataSourceConfigurationValue config = configs.get( identity );
         if ( config == null ) {
-            UnitOfWork uow = module.newUnitOfWork( UsecaseBuilder.newUsecase( "Create DataSource pool configuration" ) );
+            UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase( "Create DataSource pool configuration" ) );
 
             try {
                 DataSourceConfiguration configEntity = uow.get( DataSourceConfiguration.class, identity );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/sql/src/main/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerService.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/main/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerService.java b/libraries/sql/src/main/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerService.java
index 11e5ce5..03c04ce 100644
--- a/libraries/sql/src/main/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerService.java
+++ b/libraries/sql/src/main/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerService.java
@@ -54,6 +54,7 @@ import org.apache.zest.api.structure.Application;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.sql.datasource.DataSourceConfiguration;
 import org.apache.zest.spi.ZestSPI;
 
@@ -98,7 +99,7 @@ public interface DataSourceConfigurationManagerService
     {
 
         @Structure
-        Module module;
+        UnitOfWorkFactory uowf;
 
         @Service
         MBeanServer server;
@@ -177,7 +178,7 @@ public interface DataSourceConfigurationManagerService
             public Object getAttribute( String name )
                     throws AttributeNotFoundException, MBeanException, ReflectionException
             {
-                UnitOfWork uow = module.newUnitOfWork();
+                UnitOfWork uow = uowf.newUnitOfWork();
                 try {
                     EntityComposite configuration = uow.get( EntityComposite.class, identity );
                     AssociationStateHolder state = spi.stateOf( configuration );
@@ -195,7 +196,7 @@ public interface DataSourceConfigurationManagerService
             public void setAttribute( Attribute attribute )
                     throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
             {
-                UnitOfWork uow = module.newUnitOfWork();
+                UnitOfWork uow = uowf.newUnitOfWork();
                 try {
                     EntityComposite configuration = uow.get( EntityComposite.class, identity );
                     AssociationStateHolder state = spi.stateOf( configuration );

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/sql/src/test/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/test/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java b/libraries/sql/src/test/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
index 7af957c..e7a6f36 100644
--- a/libraries/sql/src/test/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
+++ b/libraries/sql/src/test/java/org/apache/zest/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
@@ -18,6 +18,7 @@ import java.beans.PropertyVetoException;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import javax.sql.DataSource;
+import org.apache.zest.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
 import org.junit.Assert;
 import org.junit.Test;
 import org.apache.zest.api.activation.ActivationException;
@@ -68,7 +69,7 @@ public class DataSourceConfigurationManagerServiceTest
     public void testDataSources()
         throws ActivationException, AssemblyException
     {
-        SingletonAssembler assembler = new SingletonAssembler()
+        new SingletonAssembler()
         {
             @Override
             public void assemble( ModuleAssembly module )
@@ -79,11 +80,13 @@ public class DataSourceConfigurationManagerServiceTest
                 // Create in-memory store for configurations
                 new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( module );
 
+                new DefaultUnitOfWorkAssembler().assemble( module );
+
                 // Set up DataSource service that will manage the connection pools
                 new DBCPDataSourceServiceAssembler().identifiedBy( "datasource-service" ).visibleIn( Visibility.layer ).assemble( module );
 
                 {
-                    ModuleAssembly testModule = module.layer().module( "TestDS" );
+                    ModuleAssembly testModule = module.layer().module( "TestDS" ).withDefaultUnitOfWorkFactory();
 
                     // Create a specific DataSource that uses the "datasource" service to do the main work
                     new DataSourceAssembler().
@@ -101,7 +104,7 @@ public class DataSourceConfigurationManagerServiceTest
                 }
 
                 {
-                    ModuleAssembly testModule2 = module.layer().module( "TestDS2" );
+                    ModuleAssembly testModule2 = module.layer().module( "TestDS2" ).withDefaultUnitOfWorkFactory();
 
                     // Create another specific DataSource that uses the "datasource" service to do the main work
                     // Use DataSourceAssembler to assemble the DataSource.

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/uowfile/src/main/java/org/apache/zest/library/uowfile/internal/UoWFileFactory.java
----------------------------------------------------------------------
diff --git a/libraries/uowfile/src/main/java/org/apache/zest/library/uowfile/internal/UoWFileFactory.java b/libraries/uowfile/src/main/java/org/apache/zest/library/uowfile/internal/UoWFileFactory.java
index 3dcb80a..8cdc5de 100644
--- a/libraries/uowfile/src/main/java/org/apache/zest/library/uowfile/internal/UoWFileFactory.java
+++ b/libraries/uowfile/src/main/java/org/apache/zest/library/uowfile/internal/UoWFileFactory.java
@@ -30,10 +30,10 @@ import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.service.ServiceActivation;
 import org.apache.zest.api.service.ServiceComposite;
 import org.apache.zest.api.structure.Application;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCallback;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.library.fileconfig.FileConfiguration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -60,7 +60,7 @@ public interface UoWFileFactory
         private Application app;
 
         @Structure
-        private Module module;
+        private UnitOfWorkFactory module;
 
         @This
         private ServiceComposite me;
@@ -181,5 +181,4 @@ public interface UoWFileFactory
             return uowMeta;
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFileTest.java
----------------------------------------------------------------------
diff --git a/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFileTest.java b/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFileTest.java
index 81a57f9..58e4703 100644
--- a/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFileTest.java
+++ b/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFileTest.java
@@ -22,6 +22,7 @@ import java.io.IOException;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.concern.Concerns;
@@ -31,7 +32,6 @@ import org.apache.zest.api.injection.scope.Structure;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.mixin.Mixins;
 import org.apache.zest.api.property.Property;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
 import org.apache.zest.api.unitofwork.UnitOfWorkCompletionException;
 import org.apache.zest.api.unitofwork.concern.UnitOfWorkConcern;
@@ -105,7 +105,7 @@ public class HasUoWFileTest
         implements TestService
     {
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Override
         public void modifyFile( String entityId )
@@ -148,7 +148,7 @@ public class HasUoWFileTest
         private void modifyFileImmediatly( String entityId )
             throws IOException
         {
-            TestedEntity entity = module.currentUnitOfWork().get( TestedEntity.class, entityId );
+            TestedEntity entity = uowf.currentUnitOfWork().get( TestedEntity.class, entityId );
             // START SNIPPET: api
             File attachedFile = entity.attachedFile();
             File managedFile = entity.managedFile();
@@ -190,7 +190,7 @@ public class HasUoWFileTest
         File attachedFile;
 
         // Test discarded creation
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedEntity( uow, "Testing Creation Rollback" );
             attachedFile = entity.attachedFile();
@@ -198,7 +198,7 @@ public class HasUoWFileTest
         assertFalse( "File still exists after discarded creation UoW", attachedFile.exists() );
 
         // Test completed creation
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedEntity( uow, "Testing Creation" );
             attachedFile = entity.attachedFile();
@@ -216,7 +216,7 @@ public class HasUoWFileTest
         File attachedFile;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedEntity( uow, "Testing Modification" );
             entityId = entity.identity().get();
@@ -225,14 +225,14 @@ public class HasUoWFileTest
         }
 
         // Testing discarded modification
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             testService.modifyFile( entityId );
         }
         assertTrue( "File content after discarded modification was not the good one", isFileFirstLineEqualsTo( attachedFile, "Creation" ) );
 
         // Testing completed modification
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             testService.modifyFile( entityId );
             uow.complete();
@@ -249,7 +249,7 @@ public class HasUoWFileTest
         File attachedFile;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedEntity( uow, "Testing Deletion" );
             entityId = entity.identity().get();
@@ -258,7 +258,7 @@ public class HasUoWFileTest
         }
 
         // Testing discarded deletion
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = uow.get( TestedEntity.class, entityId );
             uow.remove( entity );
@@ -266,7 +266,7 @@ public class HasUoWFileTest
         assertTrue( "File do not exists after discarded deletion", attachedFile.exists() );
 
         // Testing completed deletion
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = uow.get( TestedEntity.class, entityId );
             uow.remove( entity );
@@ -283,7 +283,7 @@ public class HasUoWFileTest
         final String entityId;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedEntity( uow, "Testing Concurrent Modification" );
             entityId = entity.identity().get();
@@ -294,11 +294,11 @@ public class HasUoWFileTest
         UnitOfWork uow, uow2;
         TestedEntity entity;
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
         entity = uow.get( TestedEntity.class, entityId );
         Inputs.text( MODIFICATION_CONTENT_URL ).transferTo( Outputs.text( entity.managedFile() ) );
 
-        uow2 = module.newUnitOfWork();
+        uow2 = uowf.newUnitOfWork();
         entity = uow2.get( TestedEntity.class, entityId );
         Inputs.text( MODIFICATION_CONTENT_URL ).transferTo( Outputs.text( entity.managedFile() ) );
 
@@ -323,7 +323,7 @@ public class HasUoWFileTest
         File attachedFile;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedEntity( uow, "Testing Concurrent Modification" );
             entityId = entity.identity().get();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFilesTest.java
----------------------------------------------------------------------
diff --git a/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFilesTest.java b/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFilesTest.java
index 782db07..7c0418c 100644
--- a/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFilesTest.java
+++ b/libraries/uowfile/src/test/java/org/apache/zest/library/uowfile/HasUoWFilesTest.java
@@ -22,6 +22,7 @@ import java.io.IOException;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.Before;
 import org.junit.Test;
 import org.apache.zest.api.concern.Concerns;
@@ -121,7 +122,7 @@ public class HasUoWFilesTest
         implements TestService
     {
         @Structure
-        private Module module;
+        private UnitOfWorkFactory uowf;
 
         @Override
         public void modifyFile( String entityId )
@@ -164,7 +165,7 @@ public class HasUoWFilesTest
         private void modifyFileImmediatly( String entityId )
             throws IOException
         {
-            TestedEntity entity = module.currentUnitOfWork().get( TestedEntity.class, entityId );
+            TestedEntity entity = uowf.currentUnitOfWork().get( TestedEntity.class, entityId );
             // START SNIPPET: api
             File attachedFileTwo = entity.attachedFile( MyEnum.fileTwo );
             File managedFileOne = entity.managedFile( MyEnum.fileOne );
@@ -205,7 +206,7 @@ public class HasUoWFilesTest
         File attachedFile;
 
         // Test discarded creation
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedOneEntityTwoFilesEntity( uow, "Testing Creation Rollback" );
             attachedFile = entity.attachedFile( MyEnum.fileOne );
@@ -213,7 +214,7 @@ public class HasUoWFilesTest
         assertFalse( "File still exists after discarded creation UoW", attachedFile.exists() );
 
         // Test completed creation
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedOneEntityTwoFilesEntity( uow, "Testing Creation" );
             attachedFile = entity.attachedFile( MyEnum.fileOne );
@@ -231,7 +232,7 @@ public class HasUoWFilesTest
         File attachedFile;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedOneEntityTwoFilesEntity( uow, "Testing Modification" );
             entityId = entity.identity().get();
@@ -240,14 +241,14 @@ public class HasUoWFilesTest
         }
 
         // Testing discarded modification
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             testService.modifyFile( entityId );
         }
         assertTrue( "File content after discarded modification was not the good one", isFileFirstLineEqualsTo( attachedFile, "Creation" ) );
 
         // Testing completed modification
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             testService.modifyFile( entityId );
             uow.complete();
@@ -264,7 +265,7 @@ public class HasUoWFilesTest
         File attachedFile;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedOneEntityTwoFilesEntity( uow, "Testing Deletion" );
             entityId = entity.identity().get();
@@ -273,7 +274,7 @@ public class HasUoWFilesTest
         }
 
         // Testing discarded deletion
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = uow.get( TestedEntity.class, entityId );
             uow.remove( entity );
@@ -281,7 +282,7 @@ public class HasUoWFilesTest
         assertTrue( "File do not exists after discarded deletion", attachedFile.exists() );
 
         // Testing completed deletion
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = uow.get( TestedEntity.class, entityId );
             uow.remove( entity );
@@ -298,7 +299,7 @@ public class HasUoWFilesTest
         final String entityId;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedOneEntityTwoFilesEntity( uow, "Testing Concurrent Modification" );
             entityId = entity.identity().get();
@@ -309,11 +310,11 @@ public class HasUoWFilesTest
         UnitOfWork uow, uow2;
         TestedEntity entity;
 
-        uow = module.newUnitOfWork();
+        uow = uowf.newUnitOfWork();
         entity = uow.get( TestedEntity.class, entityId );
         Inputs.text( MODIFICATION_CONTENT_URL ).transferTo( Outputs.text( entity.managedFile( MyEnum.fileOne ) ) );
 
-        uow2 = module.newUnitOfWork();
+        uow2 = uowf.newUnitOfWork();
         entity = uow2.get( TestedEntity.class, entityId );
         Inputs.text( MODIFICATION_CONTENT_URL ).transferTo( Outputs.text( entity.managedFile( MyEnum.fileOne ) ) );
 
@@ -338,7 +339,7 @@ public class HasUoWFilesTest
         File attachedFile;
 
         // Create new
-        try( UnitOfWork uow = module.newUnitOfWork() )
+        try( UnitOfWork uow = uowf.newUnitOfWork() )
         {
             TestedEntity entity = createTestedOneEntityTwoFilesEntity( uow, "Testing Concurrent Modification" );
             entityId = entity.identity().get();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/manual/src/main/java/org/apache/zest/manual/recipes/assemble/Docs.java
----------------------------------------------------------------------
diff --git a/manual/src/main/java/org/apache/zest/manual/recipes/assemble/Docs.java b/manual/src/main/java/org/apache/zest/manual/recipes/assemble/Docs.java
index 74de20d..03d9d5c 100644
--- a/manual/src/main/java/org/apache/zest/manual/recipes/assemble/Docs.java
+++ b/manual/src/main/java/org/apache/zest/manual/recipes/assemble/Docs.java
@@ -21,12 +21,13 @@ package org.apache.zest.manual.recipes.assemble;
 import org.apache.zest.api.injection.scope.This;
 import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.apache.zest.api.value.ValueComposite;
 
 public class Docs
 {
     @This
-    Module module;
+    UnitOfWorkFactory module;
 
     public void showUsage()
     {

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/manual/src/main/java/org/apache/zest/manual/recipes/createEntity/CarEntityFactoryMixin.java
----------------------------------------------------------------------
diff --git a/manual/src/main/java/org/apache/zest/manual/recipes/createEntity/CarEntityFactoryMixin.java b/manual/src/main/java/org/apache/zest/manual/recipes/createEntity/CarEntityFactoryMixin.java
index a6fff15..1abf6c7 100644
--- a/manual/src/main/java/org/apache/zest/manual/recipes/createEntity/CarEntityFactoryMixin.java
+++ b/manual/src/main/java/org/apache/zest/manual/recipes/createEntity/CarEntityFactoryMixin.java
@@ -20,29 +20,30 @@ package org.apache.zest.manual.recipes.createEntity;
 
 import org.apache.zest.api.entity.EntityBuilder;
 import org.apache.zest.api.injection.scope.Structure;
-import org.apache.zest.api.structure.Module;
 import org.apache.zest.api.unitofwork.UnitOfWork;
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 
 // START SNIPPET: carFactoryMixin2
 // START SNIPPET: carFactoryMixin1
 public class CarEntityFactoryMixin
-        implements CarEntityFactory
+    implements CarEntityFactory
 {
 
-// END SNIPPET: carFactoryMixin1
+    // END SNIPPET: carFactoryMixin1
     @Structure
-    Module module;
-// END SNIPPET: carFactoryMixin2
+    UnitOfWorkFactory unitOfWorkFactory;
+
+    // END SNIPPET: carFactoryMixin2
 // START SNIPPET: carFactoryMixin3
-    public CarEntityFactoryMixin( @Structure Module module )
+    public CarEntityFactoryMixin( @Structure UnitOfWorkFactory unitOfWorkFactory )
     {
     }
 
-// END SNIPPET: carFactoryMixin3
+    // END SNIPPET: carFactoryMixin3
 // START SNIPPET: createCar
-    public Car create(Manufacturer manufacturer, String model)
+    public Car create( Manufacturer manufacturer, String model )
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        UnitOfWork uow = unitOfWorkFactory.currentUnitOfWork();
         EntityBuilder<Car> builder = uow.newEntityBuilder( Car.class );
 
         Car prototype = builder.instance();

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/sampledata/BaseDataService.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/sampledata/BaseDataService.java b/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/sampledata/BaseDataService.java
index 11f76d5..7bb8a31 100644
--- a/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/sampledata/BaseDataService.java
+++ b/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/sampledata/BaseDataService.java
@@ -79,7 +79,7 @@ public interface BaseDataService
         	throws Exception
         {
             logger.debug( "CREATING BASIC DATA..." );
-            UnitOfWork uow = module.newUnitOfWork( newUsecase( "Open uow for " ) );
+            UnitOfWork uow = module.unitOfWorkFactory().newUnitOfWork( newUsecase( "Open uow for " ) );
             try
             {
 	            // UnLocode value objects
@@ -154,7 +154,7 @@ public interface BaseDataService
 
         private Location location( UnLocode unlocode, String locationStr )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = module.unitOfWorkFactory().currentUnitOfWork();
             EntityBuilder<Location> location = uow.newEntityBuilder( Location.class, unlocode.code().get() );
             location.instance().unLocode().set( unlocode );
             location.instance().name().set( locationStr );
@@ -163,7 +163,7 @@ public interface BaseDataService
 
         private Voyage voyage( String voyageNumberStr, Schedule schedule )
         {
-            UnitOfWork uow = module.currentUnitOfWork();
+            UnitOfWork uow = module.unitOfWorkFactory().currentUnitOfWork();
             EntityBuilder<Voyage> voyage = uow.newEntityBuilder( Voyage.class, voyageNumberStr );
 
             // VoyageNumber

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/infrastructure/model/EntityModel.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/infrastructure/model/EntityModel.java b/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/infrastructure/model/EntityModel.java
index e10124f..3ac14f5 100644
--- a/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/infrastructure/model/EntityModel.java
+++ b/samples/dci-cargo/dcisample_a/src/main/java/org/apache/zest/sample/dcicargo/sample_a/infrastructure/model/EntityModel.java
@@ -67,10 +67,10 @@ public class EntityModel<T extends DTO, U extends EntityComposite>
 
     private U loadEntity()
     {
-        U entity = module.currentUnitOfWork().get( entityClass, identity );
+        U entity = module.unitOfWorkFactory().currentUnitOfWork().get( entityClass, identity );
         if( entity == null )
         {
-            Usecase usecase = module.currentUnitOfWork().usecase();
+            Usecase usecase = module.unitOfWorkFactory().currentUnitOfWork().usecase();
             throw new NoSuchEntityException( EntityReference.parseEntityReference( identity ), entityClass, usecase );
         }
         return entity;

http://git-wip-us.apache.org/repos/asf/zest-java/blob/a5be013f/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestApplication.java
----------------------------------------------------------------------
diff --git a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestApplication.java b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestApplication.java
index 675a164..b22fd46 100644
--- a/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestApplication.java
+++ b/samples/dci-cargo/dcisample_a/src/test/java/org/apache/zest/sample/dcicargo/sample_a/bootstrap/test/TestApplication.java
@@ -17,6 +17,7 @@
  */
 package org.apache.zest.sample.dcicargo.sample_a.bootstrap.test;
 
+import org.apache.zest.api.unitofwork.UnitOfWorkFactory;
 import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
@@ -58,7 +59,7 @@ public class TestApplication extends BaseData
     public TestApplication()
     {
         super(app.findModule( "BOOTSTRAP", "BOOTSTRAP-Bootstrap" ));
-        Context.prepareContextBaseClass( module );
+        Context.prepareContextBaseClass( module.unitOfWorkFactory() );
     }
 
     // Printing current test method name to console
@@ -71,20 +72,25 @@ public class TestApplication extends BaseData
     {
         logger.info( name.getMethodName() );
         Usecase usecase = UsecaseBuilder.newUsecase( "Usecase: " + name );
-        module.newUnitOfWork(usecase);
+        module.unitOfWorkFactory().newUnitOfWork(usecase);
     }
 
     @After
     public void concludeTest()
     {
-        UnitOfWork uow = module.currentUnitOfWork();
+        if( module == null )
+        {
+            return;
+        }
+        UnitOfWorkFactory uowf = module.unitOfWorkFactory();
+        UnitOfWork uow = uowf.currentUnitOfWork();
         if( uow != null && uow.isOpen() )
             uow.discard();
-        if( module != null && module.isUnitOfWorkActive() )
+        if( uowf.isUnitOfWorkActive() )
         {
-            while( module.isUnitOfWorkActive() )
+            while( uowf.isUnitOfWorkActive() )
             {
-                uow = module.currentUnitOfWork();
+                uow = uowf.currentUnitOfWork();
                 if( uow.isOpen() )
                 {
                     System.err.println( "UnitOfWork not cleaned up:" + uow.usecase().name() );