How to correctly create COM classes with .NET8?
See the question and my original answer on StackOverflowFirst, you must follow what's detailed here Expose .NET Core components to COM, Generate the COM host:
Open the .csproj project file and add
<EnableComHosting>true</EnableComHosting>
inside a<PropertyGroup></PropertyGroup>
tag.
But doing this will raise "The "GenerateClsidMap" task failed unexpectedly." error, as explained here:
SYSLIB diagnostics for COM interop source generation
SYSLIB1098 .NET COM hosting with
EnableComHosting
only supports built-in COM interop. It does not support source-generated COM interop withGeneratedComInterfaceAttribute
.
GeneratedComInterfaceAttribute
is a new to .NET 8 feature, that you can't use here in this scenario (exposing and hosting your own interfaces), so you'll have to replace your code by something like this to revert back to "built-in" COM interop:
[ComVisible(true)]
[Guid("26a0aa6d-5aba-458f-92b4-b9a30ae0c65c")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface ITestBed
{
int GetXPTO();
void SetXPTO(int value);
}
[ComVisible(true)]
[Guid("3e178f98-522e-4e95-8a9c-6d80dc48b7d5")]
[ClassInterface(ClassInterfaceType.None)]
public partial class TestBed : ITestBed
{
private int _XPTO = 1024;
public int GetXPTO() => _XPTO;
public void SetXPTO(int value) => _XPTO = value;
}
Once the project is build, you can call regsvr32 <myfile>.comhost.dll
(which has been generated by .NET Core) with sufficient rights.
You cannot use the RegisterForComInterop
.csproj directive anymore as it's reserved for .NET Framework (it internally uses the same code as Regasm
which you cannot use either).
Now, if you want to use this type of object with Excel (VBA), you need a type library, either as a .TLB file or embedded in a .DLL (usually the COM server one). Unfortunately, .NET Core doesn't create one, so you must build it by yourself.
There are many ways, the official one is to create a .IDL file and use the MIDL Compiler. Another way is to continue to use .NET Framework just for regasm's capability to create a .TLB from a .cs file. Another one is to use this unofficial dscom tool (or dscom32 if you use x86) so, run
dscom tlbexport c:\mypath\COMTestBedCS.dll
and then
dscom tlbregister c:\mypath\COMTestBedCS.tlb