How can C# use a legacy DLL simply without registration(regsvr32)

Peter Kahn picture Peter Kahn · Jan 12, 2012 · Viewed 10k times · Source

Situation
I run a build system that executes many builds for many project. To avoid one build impacting another we lock down the build user to only its workspace. Builds run as a non privileged users who only have write ability to the workspace.

Challenge
During our new build we need to use a legacy 3rdparty DLL that exposes its interface through COM. The dev team wants to register the build(regsrv32.exe) but our build security regime blocks this activity. If we relax the regime then the 3rdparty DLL will impact other builds and if I have two build which need two different versions I may have the wrong build compile against the wrong version (a very real possibility).

Question
Are there any other options besides registration to handle legacy DLLs which expose their interface via COM?

Thanks for the help

Peter

Answer

David Johnston picture David Johnston · Jan 18, 2012

For my original answer to a similar question see: TFS Build server and COM references - does this work?

A good way to compile .NET code that references COM components without the COM components being registered on the build server is to use the COMFileReference reference item in your project/build files instead of COMReference. A COMFileReference item looks like this:

<ItemGroup>
  <COMFileReference Include="MyComLibrary.dll">
    <EmbedInteropTypes>True</EmbedInteropTypes>
  </COMFileReference>
</ItemGroup>

Since Visual Studio provides no designer support for COMFileReference, you must edit the project/build file by hand.

During a build, MSBuild extracts the type library information from the COM DLL and creates an interop assembly that can be either standalone or embedded in the calling .NET assembly.

Each COMFileReference item can also have a WrapperTool attribute but the default seemed to work for me just fine. The EmbedInteropTypes attribute is not documented as being applicable to COMFileReference, but it seems to work as intended.

See https://docs.microsoft.com/en-ca/visualstudio/msbuild/common-msbuild-project-items#comfilereference for a little more detail. This MSBuild item has been available since .NET 3.5.

It's a shame that no-one seems to know anything about this technique, which to me seems simpler than the alternatives. It's actually not surprising since I could only find just the one above reference to it on-line. I myself discovered this technique by digging into MSBuild's Microsoft.Common.targets file.