Search code examples
c#multithreadingcomasp.net-core-webapi

Asp.NET CORE WEB API with a COM OBJECT


I'm having issues on how to handle multiple call to my webApi.

The controllers of my webApi are using a com object who need to connect to a database and only allow one connection at a time.

Let's say i got 2 controllers :

-Clients

-Invoices

If "Clients" and "Invoices" are called at the same time, the first operation will fail.

Is it possible to make multiple Controllers wait for the end of the task ? Or is there any other solutions ?


Solution

  • Create a simple repository pattern to solve your problem. The repositories are a special kind of Facade that hide the implementation details of your database access and return domain models

    Example:

    public class DataObjectRepository: IDataObjectRepository {
          private static readonly object x = new object();
     
          public DataObject GetObject() {
              lock (x)
             {
                      // Your code accessing the COM object
              }
          }
    }
    

    Then inject it as singleton

    services.AddSingleton<IDataObjectRepository, DataObjectRepository>();
    

    Replace DataObject with any domain model name.