How to run .NET component in a singleuse way

 

We can set SingleUse for public classes in VB6 when creating VB ActiveX component , so that each interface call will raise new process to handle the request. Some customer would like to know how to implement in managed code.

Previously, an ActiveX EXE project in VB6 can define one or more SingleUse and Global SingleUse public classes. SingleUse classes differ from the more common MultiUse classes in that a new instance of the ActiveX process is created any time a client requests an instance of the class.

However, the .NET Framework doesn’t support anything similar to SingleUse classes and it isn’t easy to simulate this feature under.NET now; moreover, having a distinct process for each instance of a class impedes scalability, therefore it is recommended that you revise the overall architecture so that the application doesn’t depend on SingleUse behavior. For example, don’t use share global variables, enable your COM object as STA thread mode so that each of them will not impact each other in one process.

If your business requires generating different processes for each interface calling, we can:

Use the RegistrationServices.RegisterTypeForComClients Method in .NET, this method will finally call CoRegisterClassObject:

 

                info.cookie = regsrv.RegisterTypeForComClients(

                    type,

                    RegistrationClassContext.LocalServer,

                    RegistrationConnectionType.SingleUse);

 

 Here is one sample guide us how to do this, I tested it and works fine:

 

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.registrationservices.registertypeforcomclients(VS.80).aspx

 

To call the component from .NET client, should use:

 

    private void executeButton_Click( object sender, EventArgs e )

      {

          Type comType;

          object comObject, catObj;

          object[] par = new object[1];

          par[0] = new object();

          par[0] = "Test";

          comType = Type.GetTypeFromCLSID(new Guid("F681ABD0-41DE-46C8-9ED3-D0F4EBA19891"));

          comObject = Activator.CreateInstance(comType);

          catObj = comType.InvokeMember("Execute", System.Reflection.BindingFlags.InvokeMethod, null, comObject, null);

 ….

          }

 

If the project allows single thread to handle single object (means your object thread mode is Single Thread Apartment), you can choose ServicedComponent in .NET. Using multiple STA objects in the same DLLHOST.exe, as a solution, it is quite mature and better than singleuse.

HOW TO: Create a Serviced .NET Component in Visual C# .NET

https://support.microsoft.com/kb/306296

 

Best Regards,

Freist Li