COM+简单示例(02)

本篇文章介绍了如何用C#写一个简单的COM+组件(Dll)。

1、新建一个C# Class Library项目“CSDll”,项目增加引用“System.EnterpriseServices”

2、项目中,新增一个接口文件IJustATestCSSvc.cs,Guid要自己生成

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace CSDll
{
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    [Guid("F243B9A5-A171-49AD-AA68-47CCF6A68A2A")]
    public interface IJustATestCSSvc
    {
        int Add(int a, int b);
        String SayHiTo(String someOne);
    }
}

3、项目中,新增一个类文件JustATestCSSvc.cs,Guid要自己生成

using System;
using System.Collections.Generic;
using System.EnterpriseServices;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace CSDll
{
    
    [ComVisible(true)]
    [Guid("0C7660A9-37EC-4A39-AB0E-E936B2B24A98")]
    [ProgId("CSDll.JustATestCSSvc")]
    public class JustATestCSSvc : ServicedComponent,IJustATestCSSvc
    {

        public int Add(int a, int b)
        {
            return a + b;
        }

        public String SayHiTo(String someOne)
        {
            return "Hi " + someOne + "!";
        }
    }
}

4、项目的AssemblyInfo.cs中,增加下面几行

[assembly: ApplicationName("CSDll")]
[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ApplicationAccessControl(false,
AccessChecksLevel = AccessChecksLevelOption.ApplicationComponent)]

5、项目属性->Application->Assembly Infomation->Make Assembly COM-Visible->打勾

6、项目属性->Signing->Sign the assembly->打勾
项目属性->Signing->Choose a strong name key file->New

7、编译

8、注册

#这里一定要用正确版本的gacutil及RegAsm
C:\VBS\DNFW4\gacutil.exe /i CSCOMTest.dll
C:\VBS\DNFW4\RegAsm.exe CSCOMTest.dll
C:\VBS\DNFW4\RegSvcs.exe /c CSCOMTest.dll

9、反注册

#这里一定要用正确版本的gacutil及RegAsm
C:\VBS\DNFW4\gacutil.exe /u CSCOMTest
C:\VBS\DNFW4\RegAsm.exe /u CSCOMTest.dll
C:\VBS\DNFW4\RegSvcs.exe /u CSCOMTest.dll

10、查看注册结果(COM+)

#32位系统32位COM,64位系统64位COM
dcomcnfg
#64位系统32位COM
comexp.msc -32

Leave a Reply

Your email address will not be published. Required fields are marked *

*