Share a single EntityManager

An EntityManager is both a gateway to a service and a local cache of entities. A single EntityManager will often suffice for applications that communicate with one service and can share a single cache of entities with every application view.

We recommend encapsulating the application manager within a "datacontext" (AKA "dataservice") module and putting that datacontext where other modules - such as View Models and View Controllers - can get it. Your application's modularity pattern will guide you. For example, if your modules are attached to an application namespace, you might define a datacontext as follows:

app.datacontext = (function () {

   // ... configure the application for Breeze ...
   var manager = new breeze.EntityManager(applicationServiceName);

   // ... more datacontext ...

   var datacontext {
       getThis: getThis,
       getThat: getThat,
       saveChanges: saveChanges,
       // ... other datacontext API ...
   }
   return datacontext;

   function getThis(thisList) { ... }
   function getThat(thatList) { ... }
   function saveChanges( ) { ... }
})();

And your ViewModel classes might look somewhat like these:

/*** ViewModel of This ***/
app.ThisViewModel = (function (ko, datacontext) {

   var _activate = false,
       thisList = ko.observableArray();

   return {
       thisList: thisList,
       activate: activate,
       refresh: refresh
   };

   function activate() {
      if (!_activated) {
          _activated = true;
          refresh();
      }   
   }

   function refresh() {
      return datacontext.getThis(thisList).catch(queryFailed);   
   }

   function queryFailed(error) { ... }

})(ko, app.datacontext);
/*** ViewModel of That ***/
app.ThatViewModel = (function (ko, datacontext) {

   // ... like a ThisViewModel for that ...

})(ko, app.datacontext);