问题
在同一个单线程COM客户端中实例化两个独立的.NET COM可见类时,.NET会将它们加载到同一个AppDomain中。
我猜这是因为它们被加载到同一个线程/进程中。
此行为的一个示例显示在this GitHub repository。
中基本上,演示如下:
SetData
上的CurrentDomain
。AppDomain
属性AppDomain
获取哈希码,注意它也是相同的为什么这是一个问题?
当两个类都实现了AppDomain.CurrentDomain.AssemblyResolve
事件(或任何其他AppDomain事件)时,事件可能会相互干扰。这至少是一个并发症;我猜也许还有其他人。
想法
我认为处理此问题的最佳方法是为每个COM对象创建一个新的AppDomain。因为我无法找到(或Google)以管理方式执行此操作的方法,所以我认为可能需要在非托管代码中执行此操作。
我做了一点侦探工作。在OleView中,.NET COM可见类的InprocServer32属性为mscoree.dll
。所以,我创建了一个" shim"将其所有EXPORTS
转发到mscoree.dll的DLL。通过消除过程(消除导出直到COM不再加载),我发现mscoree
中的DllGetClassObject
负责启动.NET运行时,并返回实例化的COM对象。
所以,我能做的就是实现我自己的DllGetClassObject
,如下所示:
AppDomain
中创建对象,然后将其返回(我猜它并不像听起来那么简单)
问题
在我开始这个潜在的困难和漫长的过程之前,我想知道:
答案 0 :(得分:3)
如果代码不必在同一进程中运行,那么进程外服务器将是最简单的修复。将CLSCTX_LOCAL_SERVER
传递给CoCreateInstance
,每个类都将在dllhost
托管流程中创建。
例如在客户端:
public static object CreateLocalServer(Guid clsid)
{
return CoCreateInstance(clsid, null, CLSCTX.LOCAL_SERVER, IID_IUnknown);
}
public static object CreateLocalServer(string progid)
{
Contract.Requires(!string.IsNullOrEmpty(progid));
Guid clsid;
CLSIDFromProgID(progid, out clsid);
return CreateLocalServer(clsid);
}
enum CLSCTX : uint
{
INPROC_SERVER = 0x1,
INPROC_HANDLER = 0x2,
LOCAL_SERVER = 0x4,
INPROC_SERVER16 = 0x8,
REMOTE_SERVER = 0x10,
INPROC_HANDLER16 = 0x20,
RESERVED1 = 0x40,
RESERVED2 = 0x80,
RESERVED3 = 0x100,
RESERVED4 = 0x200,
NO_CODE_DOWNLOAD = 0x400,
RESERVED5 = 0x800,
NO_CUSTOM_MARSHAL = 0x1000,
ENABLE_CODE_DOWNLOAD = 0x2000,
NO_FAILURE_LOG = 0x4000,
DISABLE_AAA = 0x8000,
ENABLE_AAA = 0x10000,
FROM_DEFAULT_CONTEXT = 0x20000,
ACTIVATE_32_BIT_SERVER = 0x40000,
ACTIVATE_64_BIT_SERVER = 0x80000
}
[DllImport(Ole32, ExactSpelling = true, PreserveSig = false)]
[return: MarshalAs(UnmanagedType.Interface)]
public static extern object CoCreateInstance(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,
[MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter,
CLSCTX dwClsContext,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
[DllImport(Ole32, CharSet = CharSet.Unicode, PreserveSig = false)]
public static extern void CLSIDFromProgID(string progId, out Guid rclsid);
您还可以注册自定义主机,并将标准InProcServer32
换成LocalServer32
。对于示例服务器
// StandardOleMarshalObject keeps us single-threaded on the UI thread
// https://msdn.microsoft.com/en-us/library/74169f59(v=vs.110).aspx
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId(IpcConstants.CoordinatorProgID)]
public sealed class Coordinator : StandardOleMarshalObject, ICoordinator
{
public Coordinator()
{
// required for regasm
}
#region Registration
[ComRegisterFunction]
internal static void RegasmRegisterLocalServer(string path)
{
// path is HKEY_CLASSES_ROOT\\CLSID\\{clsid}", we only want CLSID...
path = path.Substring("HKEY_CLASSES_ROOT\\".Length);
using (RegistryKey keyCLSID = Registry.ClassesRoot.OpenSubKey(path, writable: true))
{
// Remove the auto-generated InprocServer32 key after registration
// (REGASM puts it there but we are going out-of-proc).
keyCLSID.DeleteSubKeyTree("InprocServer32");
// Create "LocalServer32" under the CLSID key
using (RegistryKey subkey = keyCLSID.CreateSubKey("LocalServer32"))
{
subkey.SetValue("", Assembly.GetExecutingAssembly().Location, RegistryValueKind.String);
}
}
}
[ComUnregisterFunction]
internal static void RegasmUnregisterLocalServer(string path)
{
// path is HKEY_CLASSES_ROOT\\CLSID\\{clsid}", we only want CLSID...
path = path.Substring("HKEY_CLASSES_ROOT\\".Length);
Registry.ClassesRoot.DeleteSubKeyTree(path, throwOnMissingSubKey: false);
}
#endregion
}
答案 1 :(得分:0)
嗯......这是使用工作的RGiesecke.DllExport的概念管理概念;它是否是一个好的解决方案还有待观察......所以:使用风险自负。我还在寻找更好的答案。
可以改进的一点是,我们不需要为每个实例化添加新的AppDomain
;仅适用于每个对象。我确信还有其他一些我想念的细微之处。
我们编译并注册DLL,然后使用OleView(或注册表),我们将默认的ProcServer32值更改为指向托管DLL本身。这可以通过在DLL中提供用[ComRegisterFunction()]
修饰的方法来自动化。
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;
using System.IO;
namespace Com_1
{
[Guid("F35D5D5D-4A3C-4042-AC35-CE0C57AF8383")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[ComVisible(true)]
public interface IComClass1
{
void SetAppDomainData(string data);
string GetAppDomainData();
int GetAppDomainHash();
}
//https://gist.github.com/jjeffery/1568627
[Guid("00000001-0000-0000-c000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
internal interface IClassFactory
{
void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppvObject);
void LockServer(bool fLock);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("3CA12D49-CFE5-45A3-B114-22DF2D7A0CAB")]
[Description("Sample COM Class 1")]
[ProgId("Com1.ComClass1")]
public class ComClass1 : MarshalByRefObject, IComClass1, IClassFactory
{
public void SetAppDomainData(string data)
{
AppDomain.CurrentDomain.SetData("CurrentDomainCustomData", data);
}
public string GetAppDomainData()
{
return (string)AppDomain.CurrentDomain.GetData("CurrentDomainCustomData");
}
public int GetAppDomainHash()
{
return AppDomain.CurrentDomain.GetHashCode();
}
[DllExport]
public static uint DllGetClassObject(Guid rclsid, Guid riid, out IntPtr ppv)
{
ppv = IntPtr.Zero;
try
{
if (riid.CompareTo(Guid.Parse("00000001-0000-0000-c000-000000000046")) == 0)
{
//Call to DllClassObject is requesting IClassFactory.
var instance = new ComClass1();
IntPtr iUnk = Marshal.GetIUnknownForObject(instance);
//return instance;
Marshal.QueryInterface(iUnk, ref riid, out ppv);
return 0;
}
else
return 0x80040111; //CLASS_E_CLASSNOTAVAILABLE
}
catch
{
return 0x80040111; //CLASS_E_CLASSNOTAVAILABLE
}
}
public void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppvObject)
{
IntPtr ppv = IntPtr.Zero;
//http://stackoverflow.com/a/13355702/864414
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;
var curDomEvidence = AppDomain.CurrentDomain.Evidence;
AppDomain newDomain = AppDomain.CreateDomain("MyDomain", curDomEvidence, domaininfo);
Type type = typeof(ComClass1);
var instance = newDomain.CreateInstanceAndUnwrap(
type.Assembly.FullName,
type.FullName);
ppvObject = instance;
}
public void LockServer(bool fLock)
{
//Do nothing
}
}
}