问题
A bit of an odd question and probably backwards from what most people want to do, but I'm trying to work around a legacy COM issue.
I have two components, both of which are actually .NET assemblies, but for historical reasons one is loading the other as a COM object (the assembly is registered for COM Interop). It's a plug-in architecture where the plug-in is identified by its COM ProgID, so that's the only piece of information I get to load the plug-in assembly.
One technique I've tried is:
var objType = Type.GetTypeFromProgID("My.ProgId");
var objLateBound = Activator.CreateInstance(objType);
IMyInterface netAssembly;
try
{
netAssembly = (IMyAssembly)objLateBound;
}
catch (Exception)
{
netAssembly = null;
}
If the cast to a .NET interface succeeds, the I know I have a .NET assembly and can access it through the interface. However, the technique is a bit clumsy and I'm getting problems with the COM side of things especially on 64-bit systems. I'd rather just eliminate loading the COM object and load the plug-in directly as a .NET assembly, if possible.
But the only piece of information I've got to go on is the plug-in's COM ProgID.
So, how can I go from a COM ProgID to loading a .NET Assembly, without creating any COM objects?
回答1:
Look up in the registry to find the DLL associated with the ProgID you have. Once you have its full path, load it as a normal .NET assembly:
var type = Type.GetTypeFromProgID("My.ProgId", true);
var regPath = string.Format(@"{0}\CLSID\{1:B}\InProcServer32",
Registry.ClassesRoot, type.GUID);
var assemblyPath = Registry.GetValue(regPath, "", null);
if (!string.IsNullOrEmpty(assemblyPath))
{
var assembly = Assembly.LoadFrom(assemblyPath);
// Use it as a normal .NET assembly
}
来源:https://stackoverflow.com/questions/1600714/load-a-net-assembly-from-a-com-progid-without-creating-a-com-object