Is it possible to create the single instance of COM object, and be sure all subsequent calls from any client will be made to this single instance only?
The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
To create the singleton class, we need to have static member of class, private constructor and static factory method. Static member: It gets memory only once because of static, itcontains the instance of the Singleton class. Private constructor: It will prevent to instantiate the Singleton class from outside the class.
Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.
Note that you will have to to make your COM object run Out-of-process (exposed by an EXE).
Do you really need the very same COM object used everywhere? Or do just want to control the same underlying resources from a single control point?
COM doesn't support the Singleton pattern directly, but it doesn't stricktly forbid it either. It's just that there is no registry setting that says "always serve the same object". In fact, the standard COM instantiation mechanism requires that a truly new object be returned each time you call it (this mechanism is what new
operators and CreateInstance()
use internally) . That means that to make a proper COM singleton, you cannot let your clients create it themselves. This can all be done, but it's tricky and rarely necessary.
Your best bet - funny enough - is to NOT have a COM Singleton at all. Let the client create as many different objects as it wants. Instead of a single COM object, allow multiple COM objects but make those objects "shims" which communicate with a single - internal - object implementation. Don't expose the internal singleton implementation directly as a COM object at all. You will avoid a lot of headaches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With