COM+ object per client model

Consider the following ECMAScript:

 var mather=new ActiveXObject("Arithmetic.Math")
WScript.Echo(mather.Sum(5,5))
WScript.Echo(mather.Sum(5,5))

Output is: 10 twice. No brainer.

Arithmetic.Math could be an in-process (loaded in the same process of COM Client), local (loaded in different process on the same computer) or remote (loaded in a process on different computer) COM Server. The above COM Client is unaware of this fact.

By now, Arithmetic.Math code could be the following .NET class properly registered with regasm.exe:

    public class Arithmetic.Math
    {
       public int Sum(int a, int b)
        {
           return a + b;
       }
   }

Now, we want a method to sum accumulatively and return each time the total so far:

 var mather=new ActiveXObject("Arithmetic.Math")
WScript.Echo(mather.Memorysum(5))
WScript.Echo(mather.Memorysum(5))

Output is:

 5
10

Suppose Arithmetic.Math is now the following ServicedComponent-derived class regsvcs.exe-registered within a COM+ Application activated as a Server and as a NT Service:

   public class Arithmetic.Math : System.EnterpriseServices.ServicedComponent
  {
       private int m;

      public Math()
       {
           m = 0;
      }

       public int Sum(int a, int b)
        {
           return a + b;
       }

       public int Memorysum(int n)
     {
           m += n;
         return m;
       }
   }

What happen when our client script is launched concurrently different times and Memorysum method is invoked simultaneously? What output get each?

Answer is: each client gets the same output:

 5
10

Why? Because of the COM+ object per client model, each client get its own Arithmetic.Math object.

Now suppose we want a method that sums accumulatively across different clients:

  public class Arithmetic.Math : System.EnterpriseServices.ServicedComponent
  {
       private int m;
      private static int globalm;
     private static volatile object syncroot = new object();

     public Math()
       {
           m = 0;
      }

       public int Sum(int a, int b)
        {
           return a + b;
       }

       public int Memorysum(int n)
     {
           m += n;
         return m;
       }

       public int Globalsum(int n)
     {
           lock (syncroot)
         {
               globalm += n;
           }
           return globalm;
     }
   }

What happen now when our client script is modified as below and launched concurrently different times and Globalsum method is invoked simultaneously? What output get each?

 var mather=new ActiveXObject("Arithmetic.Math")
WScript.Echo(mather.Globalsum(5))
WScript.Echo(mather.Globalsum(5))

Each output will be different now as each Arithmetic.Math object share the same state and are in the same AppDomain.