C#

How to call COM+ interface in C# program

Posted by Kerwen Blog on December 4, 2023

Create a COM+ dll

如何创建一个COM+应用程序已经在另外一篇文章中介绍过,不再赘述。
COM+

Register as COM+

当编译生成DemoCorePlus.dll后,我们有两种方式将它注册为COM+应用程序,一种是手动调用命令行,另外一种是在调用时再动态创建。第二种方式其实就是late binding,跟我们直接调用C#接口一样简单。这里我们使用第一种方式。 以Admin权限运行Developer Command Prompts, cd到bin\Release目录, 运行一下命令

1
regsvcs /fc DemoComPlus.dll

会有以下输出:

1
2
3
4
5
WARNING: The assembly does not declare an ApplicationAccessControl Attribute.  Application security will be enabled by default.
Installed Assembly:
        Assembly: C:\xxx\bin\Release\DemoComPlus.dll
        Application: DemoComPlus.Calculate
        TypeLib: C:\xxx\bin\Release\DemoComPlus.tlb

自动生成同名tlb文件,去控制面板看一下,自动生成了COM+组件
image

Create a C# program

新建一个C# console application, DemoComPlusTest, 在Program.cs里,我们通过CreateInstance方式直接调用sum接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static void Main(string[] args)
{
    try
    {
        Type objAddType = Type.GetTypeFromProgID("DemoComPlus.Calculate");
        object objAdd = Activator.CreateInstance(objAddType);

        object[] myArguments = { 11, 2 };
        object c = objAddType.InvokeMember("sum", BindingFlags.InvokeMethod, null, objAdd, myArguments);

        Console.WriteLine("Call COM+ interface, get result: " + (int)c);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed to call COM+ interface, error message: " + ex.Message);
    }

    Console.ReadKey();
}

这里我们没有引入DemoComPlus的dll或tlb文件,
如果是late binding,则需要先将DemoComPlus.dll添加为引用,然后直接调用接口

1
2
ICalculate calculate = new Calculate();
int result = calculate.sum(1, 2);

Reference

Create a COM interface
Accessing COM+ component using C#
Calling COM Components from .NET Clients