Search code examples
c#visual-studiocom

Expose C# console application functionality via COM


We have a C# console application project where we also want to expose some of its functionality via COM. What would be a sensible way to go about this?

  1. Collect common functionality in a "library" project, and add this as a reference to the console application project and a new dll (COM) project?
  2. Keep the console application project as it is, and expose methods via COM within this project (is this even possible? Can you run regasm on an exe file?)
  3. Keep the console application project as it is, add a dll (COM) project, and somehow make use of the classes in the console application project?

Solution

  • Neither the CLR nor COM actually care that your program is an EXE file instead of a DLL. Assemblies are located by their display name, that name does not include the filename extension. The CLR first looks for a file with the same name as the display name with .exe appended, then tries .dll

    So using Regasm.exe is fine, it will get loaded just like a DLL at runtime. Only differences are that your Main() method will not run. And you won't get the console window, you of course don't want one. And your [ComVisible] classes must be public, not strictly necessary when you use them in the EXE program.

    The only real casualty of doing it this way is the massive confusion the guy that takes over the job of maintaining your code will suffer from. The one that you need to treat like a homicidal maniac that knows where you live. So don't do that, option 1 is the sensible and safe one.