需要辛格尔顿COM对象格尔、对象、COM

2023-09-04 11:47:39 作者:十里平湖霜满天

是否有可能创建COM对象的单个实例,并确保从任何客户端的所有后续调用将作出这种单一实例而已?

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?

推荐答案

请注意,你必须让你的COM对象运行Out的进程(通过一个EXE曝光)。

Note that you will have to to make your COM object run Out-of-process (exposed by an EXE).

你真的需要到处使用同样的COM对象?还是只是想从一个单一的控制点控制相同的底层资源?

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不支持Singleton模式的直接,但它并没有stricktly禁止它的。这只是没有注册表设置,上面写着永远服务于同一个对象。事实上,标准的COM实例化机制的需要的是一个真正的新对象中每次调用它(这个机制是什么运营商和时间返回的CreateInstance()内部使用)。这意味着,以作出正确的COM单身,你不能让你的客户创建它自己。这都是可以做的,但它是棘手的,很少有必要的。

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.

您最好的选择 - 够滑稽的 - 是不是有一个COM辛格尔顿都没有。让客户创造尽可能多的不同的对象,因为它希望。相反,一个COM对象,允许多个COM对象,但使这些对象垫片,它与单个交流 - 内部 - 对象实现。不要直接暴露出内部单执行作为COM对象都没有。你会避免很多麻烦。

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.