GlobalCache / Alternative to GlobalVariables in X++
Many times because of flawed implementation designs, we
often need global variables. We may use a table with a key field and a
container field for this purpose, but the simplest way of doing this will be
using a Global Cache.
The SysGlobalCache class is used by Axapta to
store "global" variables and object references. It is implemented as
a standard class in the AOT and uses a simple caching mechanism
involving nested Map.
It is possible to create and use
SysGlobalCache objects to implement your own local caching, or to use the
instances automatically available through infolog.globalCache() (client-side)
andappl.globalCache() (server-side).
A global cache is an instance of class - SysGlobalCache, which is nothing but a Map containing Maps with Userid as Key. These Maps contain the actual value and a key.
In Ax, we have three(infact 4) Global Caches - Infolog.globalCache(), Appl.globalCache(), ClassFactory.GlobalCache().
How to use:
To Set a Value:
static void GlobalCacheSet(Args _args)
{
SysGlobalCache globalCache;
;
globalCache = ClassFactory.globalCache();
globalCache.set(curuserid(), 1, "One");
}
To Get the Value:
static void GlobalCacheGet(Args _args)
{
SysGlobalCache globalCache;
;
globalCache = ClassFactory.globalCache();
print globalCache.get(curuserid(), 1);
globalcache.remove(curuserid(), 1);
pause;
}
In the above the example, we can also use Infolog.globalCache() or Appl.globalCache().
Why do we have three Caches?
Its simple, the term "Caching" comes when there is something to do with Performance.
Infolog Object resides in Client and Application Object resides in Server.
To share your global variable across the network and accept the performance penalty of a client/server call, use the infolog variable (Info class) or appl variable (Application class) instead of ClassFactory.
ClassFactory is a special class, which has instances residing at both server and client. At run time, two instances of the ClassFactory class exist, and they share name classFactory. However confusing the implementation details might sound, this is a powerful concept. When you call a method on classFactory from code running on the client, you are calling the classFactory object on the client tier; when you call a method on classFactory from code running on the server, you are calling the classFactory object on the server tier. Remember this when debugging the ClassFactory class.
Happy Daxing J
Leave a Comment