如果安装程序未使用默认机制注册 COM 对象,您可以尝试使用自定义操作强制进行注册。此技术的另一个好处是您可以单步执行自定义操作以了解正在发生的情况。
在你的项目中添加一个继承自Installer的类,用这个属性来装饰
[RunInstaller(true)]
并重写以下一种或多种方法:
Install()
Uninstall()
Commit()
Rollback()
下面是使用 COM Interop 执行注册的完整示例。它散布着跟踪输出(与某些观点相反),这些输出将显示在 Sysinternals DebugVw 中。当构建在调试配置中时,它将弹出一个对话框,允许您附加调试器并单步执行自定义操作。
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace TiGra
{
/// <summary>
/// Custom install actions that must be carried out during product installation.
/// </summary>
[RunInstaller(true)]
public class MyInstaller : Installer
{
/// <summary>
/// Custom Install Action that performs custom registration steps as well as
/// registering for COM Interop.
/// </summary>
/// <param name="stateSaver">Not used<see cref="Installer"/></param>
public override void Install(System.Collections.IDictionary stateSaver)
{
Trace.WriteLine("Install custom action - Starting registration for COM Interop");
#if DEBUG
MessageBox.Show("Attach debugger to this process now, if required", "Custom Action Debug", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
#endif
base.Install(stateSaver);
RegistrationServices regsrv = new RegistrationServices();
if (!regsrv.RegisterAssembly(this.GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
{
Trace.WriteLine("COM registration failed");
throw new InstallException("Failed To Register for COM Interop");
}
Trace.WriteLine("Completed registration for COM Interop");
}
/// <summary>
/// Custom Install Action that removes the COM Interop component registrations.
/// </summary>
/// <param name="savedState">Not used<see cref="Installer"/></param>
public override void Uninstall(System.Collections.IDictionary savedState)
{
Trace.WriteLine("Uninstall custom action - unregistering from COM Interop");
try
{
base.Uninstall(savedState);
RegistrationServices regsrv = new RegistrationServices();
if (!regsrv.UnregisterAssembly(this.GetType().Assembly))
{
Trace.WriteLine("COM Interop deregistration failed");
throw new InstallException("Failed To Unregister from COM Interop");
}
}
finally
{
Trace.WriteLine("Completed uninstall custom action");
}
}
}
}
最后一件事要做。除非安装程序配置为执行自定义操作,否则自定义操作不会运行。就是这样:
- In your Visual Studio installer project, right click on the project name and select View -> Custom Actions. You'll see a tree view something like this:
- Custom Actions
- Install
- 卸载
- Commit
- Rollback
- 右键单击最顶部的节点(自定义操作)并选择添加自定义操作.
- 导航到包含用 [RunInstaller(true)] 属性修饰的类的文件或项目输出,突出显示它并单击“确定”。
- 然后,您的项目输出应该出现在四个节点的每一个下。这意味着您的自定义操作类将在四个安装程序阶段的每个阶段中被调用。
如果您需要对此进行更好的控制,您可以将自定义操作类添加到某些安装程序阶段,但不能添加到其他阶段。例如,如果安装和卸载由不同的程序集处理,则您可以在“安装”和“提交”节点下添加一个程序集,在“卸载”和“回滚”节点下添加另一个程序集。
就是这样,现在将在设置过程中调用您的自定义操作。调试自定义操作的快速提示。在调试版本中使用条件指令(如上例所示)显示消息框。此消息框将在设置过程中显示。这会有效地暂停安装过程,直到您在消息框中单击“确定”,这为您提供了将调试器附加到 msiexec.exe 进程的“机会之窗”(双关语)。将会有多个 msiexec.exe 进程在运行,您需要选择一个显示为托管代码的进程。调试器将连接,并且您的断点将“亮起”,因此您可以拦截执行并单步执行自定义操作。