mpen
mpen

Reputation: 282855

TargetInvocationException?

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.

Upvotes: 1

Views: 9218

Answers (3)

Igor Zevaka
Igor Zevaka

Reputation: 76500

Just a suggestion. Can you add a default constructor to the class and see what happens? Like so:

public DownloadManager()
{
   this.dispatcher = Dispatcher.CurrentDispatcher;
}

I wonder if XAML doesn't like a constructor with parameters with default values.

Upvotes: 1

Adam Sills
Adam Sills

Reputation: 17062

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):

public MyViewModel()
    : this( null ) {
}

public MyViewModel( Dispatcher dispatcher = null ) {
    this._dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
}

Upvotes: 3

Preet Sangha
Preet Sangha

Reputation: 65496

None that I can see directly, however look in the InnerException if there is one, what does it say?

Upvotes: 1

Related Questions