.NET Core error on build: error MSB4062 Microsoft.

2020-08-11 04:54发布

问题:

I'm working on a .net core web app (targeting net461). The app needs to reference a COM dll.

I added the COM reference and the app still builds on my dev machine. However, on the build server it fails to build with this error:

C:\Program Files (x86)\dotnet\sdk\2.0.0\Microsoft.Common.CurrentVersion.targets(2604,5): error MSB4062: The "Microsoft.Build.Tasks.ResolveComReference" task could not be loaded from the assembly Microsoft.Build.Tasks.Core

After searching a bit, it seems like it's a pretty uncommon error. Anyone know what the error is and/or how to fix it?


UPDATE: Seems like the dotnet CLI does not support COM references. Visual Studio uses msbuild directly behind the scenes, but on the build server, I was using the dotnet CLI commands.

WORKAROUND:

  1. Reference the COM dll and rebuild. Visual Studio will generate an interop dll. It will be named something like Interop.MyComDLL.dll. It is found in the build output directory.
  2. Copy the generated Interop dll to somewhere in the application (I just used a /dlls folder at the root application level).
  3. Remove the COM dll reference.
  4. Add a direct reference (Dependencies > Add Reference... > Browse in Visual Studio) to the Interop dll

回答1:

It should also fail on developer machine if you try to build it using the same command as on build server, e.g.

dotnet.exe build Solution.sln --configuration Release --no-incremental

VS building solution using msbuild, it's a different way.



回答2:

My suggestion would be to do any COM interop using dynamics, if you want to make it easier to change in the future, create an interface that that has all the COM properties and methods you need to access.

Create a class, implementing the interface, that creates the COM Object dynamically as part of the constructor. Then implement each of the methods and properties to access the the dynamic object you created.

This should remove any build time dependency, give an interface the rest of your code can depend on, and give an easy way out of the COM at a later date if required.

You might also find Rick Strahl's article for COM in .Net Core useful?

https://weblog.west-wind.com/posts/2019/Jan/22/COM-Object-Access-and-dynamic-in-NET-Core-2x

Hope this helps :)