Properly Disposing of Workflow Add-Ins

Even an exceedingly simple add-in, in this case a label and a message box, can have significant side effects when paired with workflows.

http://screencast.com/t/pnriTy8J

In the video you see that each time the workflow loads a workspace the message box is displayed an extra time. This is because the previous versions of
the add-in still exist and are being loaded even though they are no longer being displayed.

This happens because the add-in component is properly disposed, but the record context it exposes isn't. The dataLoaded event is never unsubscribed and thus continues
to be called whenever the workspace loads even though there is no loner a component for it.

Thankfully the solution is relatively simple: implement IDisposable on your component and manually dispose of your control and remove the data loaded listener:

public class Control : IWorkspaceComponent2, IDisposable
{
private WorkspaceControl control;

//removed for brevity

public void Dispose()
{
if (control.IsDisposed == false && control.Disposing == false)
{
if (inDesignMode == false)
context.DataLoaded -= context_DataLoaded;

control.Dispose();
}
}
}

Now when the workflow changes workspaces only a single message box will be displayed.

Source code for this demo (and a similar implementation using a single class for the UserControl and the WorkspaceComponent) can be found in BitBucket under / AddIns / DisposableAddIn /

Zircon - This is a contributing Drupal Theme
Design by WeebPal.