regasm.exe /tlb /codebase component.dll
在这种情况下,使用/tlb开关生成类型库是必需的,否则我将无法从该程序集中创建对象。
问题是,如何配置我的Visual Studio 2008安装项目以通过调用regasm /tlb来注册此程序集?
您可以使用System.Runtime.InteropServices.RegistrationServices,而无需手动调用regasm.exe:
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
RegistrationServices regsrv = new RegistrationServices();
if (!regsrv.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
{
throw new InstallException("Failed to register for COM Interop.");
}
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
RegistrationServices regsrv = new RegistrationServices();
if (!regsrv.UnregisterAssembly(GetType().Assembly))
{
throw new InstallException("Failed to unregister for COM Interop.");
}
}
卸载时也会注销该库。
覆盖Install,Commit和Uninstall方法,添加:
//获取regasm的位置
string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
// 获取我们DLL的位置
string componentPath = typeof(RegisterAssembly).Assembly.Location;
// 执行regasm
System.Diagnostics.Process.Start(regasmPath, "/codebase /tlb \"" + componentPath + "\"");
在卸载操作中将/codebase /tlb替换为/u。
你可以在以下网站找到一个实际类的演示:http://leon.mvps.org/DotNet/RegasmInstaller.html
我最初尝试从安装程序进程中运行regasm(在看到这篇文章之前)。尝试运行regasm并处理所有错误是有问题的,即使不尝试处理Windows 7的提升权限。
使用Runtime.InteropServices.RegistrationServices.RegisterAssembly
更简洁,提供了更好的错误捕获。
Visual Studio安装程序仅进行COM类注册,但默认情况下不进行类型库生成和注册(这是regasm.exe
中/tlb
开关所做的)。至少在Visual Studio 2017中,通过使用Tlbexp.exe
实用程序在DLL的后期构建步骤中生成类型库就足够了。
如果安装程序项目在与要安装的库相同的目录中发现扩展名为.tlb
且名称相同的文件,则会自动将其包含在设置项目中并在安装过程中执行注册步骤。当然,也可以手动生成.tlb
文件并将其包含在设置项目中(并将其Register属性设置为vsdrfCOM
)。
这里有一篇很棒的文章,介绍了C#和COM接口,上述信息来自它的部署章节。