Why would the following lines of code cause a TargetInvocationException exception?
private Dispatcher dispatcher = null;
public DownloadManager(Dispatcher dispatcher = null)
{
this.dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
}
When the DownloadManager is instantiated in the XAML like:
<Window.DataContext>
<c:DownloadManager />
</Window.DataContext>
Note that the debugger doesn’t specifically highlight any of these lines; all I know is that if I delete them, my program doesn’t crash.
To instantiate an object through XAML, it needs to have a public default constructor. A parameterized constructor with default values is not the same as a default constructor. As such, the XAML parser is dying when trying to instantiate your object. I’d say a TargetInvocationException with a NullReferenceException as the inner is a bit worthless and something more useful could be thrown as the inner.
Finally, FWIW, the XAML editor in VS2010 is telling me that my Type is unusable without a default constructor when I have a constructor defined like yours.
Use two constructors instead (or just a default constructor):