需要单例 COM 对象
是否可以创建 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,您必须使 COM 对象在进程外运行(由 EXE 公开)。
您真的需要到处使用相同的 COM 对象吗?或者只想从单个控制点控制相同的底层资源?
COM不直接支持单例模式,但也没有严格禁止它。只是没有注册表设置表明“始终服务于同一对象”。事实上,标准 COM 实例化机制要求每次调用时都返回一个真正的新对象(这种机制就是
new
运算符和CreateInstance()< /code> 内部使用)。这意味着要创建正确的 COM 单例,您不能让您的客户自己创建它。这一切都可以完成,但是很棘手并且很少有必要。
你最好的选择——足够有趣——就是根本不使用 COM Singleton。让客户端创建任意数量的不同对象。允许多个 COM 对象,而不是单个 COM 对象,但使这些对象成为与单个内部对象实现进行通信的“垫片”。根本不要将内部单例实现直接公开为 COM 对象。你会避免很多令人头疼的事情。
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 andCreateInstance()
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.