简体   繁体   English

使用excel插件防止单个对象的多个实例

[英]Preventing multiple instances of a singleton object with excel plugins

I've got two pieces of technology that plug into excel. 我有两项可插入excel的技术。

One is a COM Addin that implements the IDTExtensibility2 interface. 一个是实现IDTExtensibility2接口的COM插件。 Another is an RTD server that is implemented via Excel-DNA. 另一个是通过Excel-DNA实现的RTD服务器。

Both of these objects are instantiated by excel. 这两个对象都由excel实例化。 Each of them needs to access a third object at runtime to get data from and push it to excel. 他们每个人都需要在运行时访问第三个对象以从中获取数据并将其推送到excel。

Since I can't hand this object to the excel plugins I've made it a singleton with the hope that each of them could share the same instance. 由于我无法将此对象交给excel插件,因此我将其设为单例,希望它们每个都可以共享同一实例。

Unfortunately when running the code, each of them don't see the instance of the singleton object that the other has created. 不幸的是,在运行代码时,它们每个都看不到另一个创建的单例对象的实例。

How can I get both addins to reference the same object? 如何获得两个加载项以引用同一对象?

Let's work under the assumption that both addins need to remain and I'd rather not go to an interprocess communication setup. 让我们假设两个附加组件都需要保留,而我不想去进行进程间通信设置。

TL/DR Two excel plugins need to share a 3rd object, but making the third object a singleton doesn't work as each excel plugin doesn't see the instance of the third object that the other plugin created. TL / DR两个excel插件需要共享一个第三个对象,但是使第三个对象成为单例是不起作用的,因为每个excel插件都看不到另一个插件创建的第三个对象的实例。

What is the solution to such a problem? 解决这个问题有什么办法?

You add-ins are loading in separate AppDomains. 您的加载项正在单独的AppDomain中加载。 One option is to integrate the COM Add-In into the Excel-DNA add-in. 一种选择是将COM加载项集成到Excel-DNA加载项中。 This might be as easy as: 这可能很简单:

  1. Add your COM add-in code to your Excel-DNA project, 将您的COM加载项代码添加到Excel-DNA项目中,
  2. Change your add-in class to derive from ExcelComAddIn (instead of IDTExtensibility2 ), 更改您的外接程序类以派生自ExcelComAddIn (而不是IDTExtensibility2 ),
  3. Load that class in your AutoOpen via ExcelComAddInHelper.LoadComAddIn(...) . 通过ExcelComAddInHelper.LoadComAddIn(...)AutoOpen加载该类。

Otherwise you will need some sort of inter-AppDomain communication. 否则,您将需要某种形式的AppDomain间通信。 You can set up a Marshal-By-Reference object that you set to the Object property of the COMAddIn object corresponding to your loaded add-in, and retrieve that using the COM interfaces from the Excel-DNA add-in. 您可以设置一个Marshal-By-Reference对象,该Object设置为与加载的加载项相对应的COMAddIn对象的Object属性,然后使用COM接口从Excel-DNA加载项中检索该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM