Introduction
I summarized some best practice rules in writing a COM-visible assembly according to my recent work.
- In AssemblyInfo.cs, I wrote two attributes:
[assembly: ComVisible(false)]
[assembly: Guid("64729ced-7a8d-4c90-af7f-a41725cfe216")]
They indicated I didn’t want all public
classes to be COM-visible and I didn’t want Visual Studio to implicitly generate a random GUID
as my library ID.
- I unchecked the “Register for COM interop” box in the project’s Build option because I didn’t want Visual Studio to register the assembly on the build machine.
- I wrote each COM-visible class like the following example:
[ComVisible(true)]
[Guid("7884998B-0504-4CBE-9FF9-6BBAA9776188")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("MyNamespace.MyClass")]
public class MyClass : IMyClass
{
}
Here, I explicitly declared the class as COM-visible and gave it a GUID
as the class ID. Visual Studio would generate a random GUID
if I didn’t specify one. I used ClassInterfaceType.None
to prevent Visual Studio from generating an interface for the class automatically. The automatic behavior would expose methods which I didn’t want to expose and could introduce unwanted method declarations.
By the way, you can explicitly specify the ProgId
attribute. By default, namespaces and class name will be combined as the ProgId of the class.
- I declared an interface for each COM-visible class explicitly like the following example:
[ComVisible(true)]
[Guid("67F6AA4C-A9A5-4682-98F9-15BDF2246A74")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IMyClass
{
}
There was no special rule for InterfaceType
. It would depend on application needs. And I only declared the methods which I wanted to expose in the interface.
CodeProject