Let's assume I have a WinForms Component.
It can be a class based on the System.ComponentModel.Component or System.Windows.Forms.Control class (actually Control inherits Component).
My Component may use other .NET classes we should dispose correctly - Pens, Brushes, ContextMenuStrips and the like. I dispose them as expected in an implementation of the Dispose(bool disposing) method according to the well-known IDisposable pattern.
I wonder, when I must add a special constructor accepting an IConatiner parameter so the Form Designer will register an instance of my Component for automatic resource disposal during the Form shutdown:
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
...
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
I analyzed the source code of the Dispose(bool disposing) method of some WinForms Component trying to find an answer, but the situation is still not clear.
For example, the ContextMenuStrip Component has such a constructor, but DataGridView doesn't - though both has enough objects they dispose in their Dispose(bool disposing) implementations.
Any hints or ideas?