Exposing .NET Core components to COM - .NET (2024)

  • Article

This article walks you through how to expose a class to COM from .NET Core (or .NET 5+). This tutorial shows you how to:

  • Expose a class to COM from .NET Core.
  • Generate a COM server as part of building your .NET Core library.
  • Automatically generate a side-by-side server manifest for Registry-Free COM.

Prerequisites

  • Install .NET Core 3.0 SDK or a newer version.

Create the library

The first step is to create the library.

  1. Create a new folder, and in that folder run the following command:

    dotnet new classlib
  2. Open Class1.cs.

  3. Add using System.Runtime.InteropServices; to the top of the file.

  4. Create an interface named IServer. For example:

    using System;using System.Runtime.InteropServices;[ComVisible(true)][Guid(ContractGuids.ServerInterface)][InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]public interface IServer{ /// <summary> /// Compute the value of the constant Pi. /// </summary> double ComputePi();}
  5. Add the [Guid("<IID>")] attribute to the interface, with the interface GUID for the COM interface you're implementing. For example, [Guid("fe103d6e-e71b-414c-80bf-982f18f6c1c7")]. Note that this GUID needs to be unique since it is the only identifier of this interface for COM. In Visual Studio, you can generate a GUID by going to Tools > Create GUID to open the Create GUID tool.

  6. Add the [InterfaceType] attribute to the interface and specify what base COM interfaces your interface should implement.

  7. Create a class named Server that implements IServer.

  8. Add the [Guid("<CLSID>")] attribute to the class, with the class identifier GUID for the COM class you're implementing. For example, [Guid("9f35b6f5-2c05-4e7f-93aa-ee087f6e7ab6")]. As with the interface GUID, this GUID must be unique since it is the only identifier of this interface to COM.

  9. Add the [ComVisible(true)] attribute to both the interface and the class.

Important

Unlike in .NET Framework, .NET Core requires you to specify the CLSID of any class you want to be activatable via COM.

  1. Open the .csproj project file and add <EnableComHosting>true</EnableComHosting> inside a <PropertyGroup></PropertyGroup> tag.
  2. Build the project.

The resulting output will have a ProjectName.dll, ProjectName.deps.json, ProjectName.runtimeconfig.json and ProjectName.comhost.dll file.

Register the COM host for COM

Open an elevated command prompt and run regsvr32 ProjectName.comhost.dll. That will register all of your exposed .NET objects with COM.

If you intend to embed a type library (TLB), it's recommended to also define functions using ComRegisterFunctionAttribute and ComUnregisterFunctionAttribute. These functions can be used to register and unregister the TLB for the COM server. For a complete example, see the OutOfProcCOM sample.

Enabling RegFree COM

  1. Open the .csproj project file and add <EnableRegFreeCom>true</EnableRegFreeCom> inside a <PropertyGroup></PropertyGroup> tag.
  2. Build the project.

The resulting output will now also have a ProjectName.X.manifest file. This file is the side-by-side manifest for use with Registry-Free COM.

Embedding type libraries in the COM host

Unlike in .NET Framework, there is no support in .NET Core or .NET 5+ for generating a COM Type Library (TLB) from a .NET assembly. The guidance is to either manually write an IDL file or a C/C++ header for the native declarations of the COM interfaces. If you decide to write an IDL file, you can compile it with the Visual C++ SDK's MIDL compiler to produce a TLB.

In .NET 6 and later versions, the .NET SDK supports embedding already-compiled TLBs into the COM host as part of your project build.

To embed a type library into your application, follow these steps:

  1. Open the .csproj project file and add <ComHostTypeLibrary Include="path/to/typelib.tlb" Id="<id>" /> inside an <ItemGroup></ItemGroup> tag.
  2. Replace <id> with a positive integer value. The value must be unique among the TLBs you specify to be embedded in the COM host.
    • The Id attribute is optional if you only add one ComHostTypeLibrary to your project.

For example, the following code block adds the Server.tlb type library at index 1 to the COM host:

<ItemGroup> <ComHostTypeLibrary Include="Server.tlb" Id="1" /></ItemGroup>

Loading in the default AssemblyLoadContext

During activation, the assembly containing the COM component is loaded in a separate AssemblyLoadContext based on the assembly path. If there is one assembly providing multiple COM servers, the AssemblyLoadContext is reused such that all of the servers from that assembly reside in the same load context. If there are multiple assemblies providing COM servers, a new AssemblyLoadContext is created for each assembly, and each server resides in the load context that corresponds to its assembly.

In .NET 8 and later versions, the assembly can specify that it should be loaded in the default AssemblyLoadContext. To enable loading in the default context, add the following RuntimeHostConfigurationOption item to the project:

<ItemGroup> <RuntimeHostConfigurationOption Include="System.Runtime.InteropServices.COM.LoadComponentInDefaultContext" Value="true" /></ItemGroup>

Sample

There is a fully functional COM server sample in the dotnet/samples repository on GitHub.

Additional notes

Important

In .NET Framework, an "Any CPU" assembly can be consumed by both 32-bit and 64-bit clients. By default, in .NET Core, .NET 5, and later versions, "Any CPU" assemblies are accompanied by a 64-bit *.comhost.dll. Because of this, they can only be consumed by 64-bit clients. That is the default because that is what the SDK represents. This behavior is identical to how the "self-contained" feature is published: by default it uses what the SDK provides. The NETCoreSdkRuntimeIdentifier MSBuild property determines the bitness of *.comhost.dll. The managed part is actually bitness agnostic as expected, but the accompanying native asset defaults to the targeted SDK.

Self-contained deployments of COM components are not supported. Only framework-dependent deployments of COM components are supported.

Additionally, loading both .NET Framework and .NET Core into the same process does have diagnostic limitations. The primary limitation is the debugging of managed components as it is not possible to debug both .NET Framework and .NET Core at the same time. In addition, the two runtime instances don't share managed assemblies. This means that it isn't possible to share actual .NET types across the two runtimes and instead all interactions must be restricted to the exposed COM interface contracts.

Exposing .NET Core components to COM - .NET (2024)

FAQs

Can I reference .NET Core from .NET Framework? ›

The compatibility mode allows . NET Standard and . NET projects to reference . NET Framework libraries as if they were compiled for the project's target framework.

Can .NET and .NET Core coexist? ›

NET Framework and . NET Core are used together in systems that take advantage of the strengths of both stacks. If you'd like to learn more and perhaps get involved, here are a few places to get started: .

Is .NET Core backwards compatible with .NET Framework? ›

NET implementations, developers expect a high level of compatibility across versions of a given implementation of . NET. In particular, code written for an earlier version of . NET Core should run seamlessly on .

How do I change .NET Core to .NET standard in Visual Studio? ›

Using the Visual Studio . NET Portability Analyzer extension
  1. In Visual Studio, select Analyze and then Portability Analyzer Settings.
  2. In the General Settings window, select . NET Standard 2.0 under Target Platforms, and then choose OK.
  3. Now, open the project file containing the code that needs to target .
Apr 19, 2024

Can you migrate from .NET Framework to .NET Core? ›

You can migrate your old project to the Core project using the 'dotnet migrate; command, which migrates the project. json and any other files that are required by the web application. The dotnet migrate command will not change your code in any way.

How do I reference a .NET Core? ›

One method of adding references to your library is by typing it directly in the project. json file. As you can see that we have added some references under the dependencies section as shown in the following code. Let us now save this file and you will see that references are added to your library now.

Is .NET Core being discontinued? ›

NET Core Framework is slated to go out of support on December 13th, 2022. Microsoft recommends upgrading . NET Core 3.1 applications to . NET 6.0 to stay supported for the future, while the developers have mixed feelings about the .

What are the disadvantages of .NET Core? ›

Disadvantages of . NET Core
  • Limited libraries and third-party tools: Although it's catching up, . ...
  • Less community support: Being relatively new, . ...
  • No support for web forms: If your existing applications rely on web forms, you'll need to look for alternatives or stick with .

Is .NET Core faster than .NET Framework? ›

. NET Core is a lot faster than the . NET Framework due to its modular architecture. It offers lighter versions of core framework components leading to simplified cross-platform app development.

Can I install .NET Framework and .NET Core on the same machine? ›

Side-by-side installation isn't possible with . NET Framework. It's a Windows component, and only one version can exist on a machine at a time: each version of . NET Framework replaces the previous version.

Which technology is discontinued in .NET Core? ›

Across machines, Microsoft recommends “a low-overhead plain text protocol such as HTTP”. Thus Microsoft has no plans to include Remoting in . NET Core. Most of the serializer such as data contract serialization, XML serialization, JSON.NET, and protobuf-net will be supported in .

Which versions of .NET Framework are obsolete? ›

NET Framework 4.5. 2, 4.6, and 4.6. 1 retired on April 26, 2022. These specific releases were previously signed using Secure Hash Algorithm (SHA-1) certificates.

How do I change the .NET framework in Visual Studio? ›

Change the target framework
  1. In Solution Explorer, open the right-click context menu for the project that you want to change, and then choose Properties.
  2. In the left column of the Properties window, choose the Application tab. ...
  3. In the Target Framework list, choose the version that you want.
Dec 12, 2023

How to change .NET Core version in Visual Studio? ›

Here's how to do it:
  1. Open the project file (the *.csproj , *.vbproj , or *.fsproj file).
  2. Change the <TargetFramework> property value from, for example, net6.0 to net8.0 .
  3. The same pattern applies for the <TargetFrameworks> property if it is being used.
May 14, 2024

Which Visual Studio for NET Core? ›

.NET/.NET Core. .NET is a free, cross-platform, open-source developer platform for building many different types of applications. Visual Studio 2022 SDK. The software development kit (SDK) includes everything you need to build and run .NET applications, using command-line tools and any editor (like Visual Studio).

Can we refer a NET Core DLL in .NET Framework? ›

It absolutely works, easily and well. You simply reference your old project or built assembly from your . Net 6 assembly and use it like normal. You don't have to do anything special at all.

Is .NET Core replace .NET Framework? ›

Yes, Microsoft has indicated that . NET Core will eventually replace the . NET Framework. With the introduction of .

Is .NET compatible with .NET Core? ›

.NET and .NET Core are supported across several operating systems and versions. The .NET Supported OS Policy provides current details on operating systems support policies and versions.

What is the difference between .NET Core and .NET Framework? ›

. Net Core does not support desktop application development and it rather focuses on the web, windows mobile, and windows store. . Net Framework is used for the development of both desktop and web applications as well as it supports windows forms and WPF applications.

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 5519

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.