Search code examples
c#asp.netcomasp.net-web-api2

How to cache COM Object to not create/dispose it for each request?


I have an asp.net web-api2 application which is using COM object for interacting with data. I have an Engine object that is working with it. Like this:

public class PVXEngine : IDisposable
{
    protected DispatchObject _pvxObject;
    public PVXEngine()
    {
       _pvxObject = new DispatchObject("ProvideX.Script");
    }

    public void Dispose()
    {
       _pvxObject.Dispose();
    }
}

I don't want to recreate this object for every request. How can i store my PVXEngine in my Application Context to not recreate it. ( I guess it will be disposed when Application Pool Recyles. )

Also if it is possible, refer me documentation where I can read about caching objects in Application Pool.

Thank you for your time.


Solution

  • Make the PVXEngine a class variable. This assumes that the object is thread safe.

     public class PVXEngine : IDisposable
     {
         static protected DispatchObject _pvxObject = new DispatchObject("ProvideX.Script");
     }
    

    If the object is not thread safe then I suggest using a resource pool as specified in C# Object Pooling Pattern implementation.