I am creating an ASP.NET Web API gateway which needs to communicate to legacy COM component business logic written in C++. So I am creating another Web API which internally gets data from COM component through C# CLI layer.
Hence C++ COM component is not thread safe, I am considering to span multiple instances of WEB API per user request. The outer Web API Gateway can be instantiate the inner Web API per user and request to it.
Do any API gateways like Ocelot have any feature to achieve spanning multiple instance of same Web API? Or how to achieve spanning multiple instances and make request?
Like already mentioned by the comment thread, you can load your COM model in a single-thread appartment state. If it's a legacy COM component, you have two major options to achieve it: either via registry or via your code.
A. If the COM component is correctly deployed and registered, you can change the appartment state via the registry with ThreadingModel 'Apartment' being a single-thread apartment.
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID
{CLSID}
InprocServer32
(Default) = path
ThreadingModel = Apartment
B. The other way is programmatically instantiate the COM component in a single-thread apartment, which would look somehow like this in your code:
using System.Runtime.InteropServices;
// create a new thread in single-thread apartment state
var staThread = new Thread(LoadCOMComponent);
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
static void LoadCOMComponent()
{
try
{
var comType = Type.GetTypeFromProgID("yourobject");
// activate COM object
var comObject = Activator.CreateInstance(comType);
// use COM object
[your code]
// release COM object
Marshal.ReleaseComObject(comObject);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}