Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF and Unity - No matching constructor found on type

I want to use Unity in my WPF application using VS2012, I defined unity container as follows:

IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<IMainViewModel, MainViewModel>();
var window = unityContainer.Resolve<MainWindow>();
window.Show();

My window constructor looks as follows:

public MainWindow(IMainViewModel mainViewModel)
       {
            InitializeComponent();
            this.DataContext = mainViewModel;
        }

When I run the application I get the following error:

An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: 'No matching constructor found on type 'WPFClient.MainWindow'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '3' and line position '9'.

What am I doing wrong?

like image 669
niao Avatar asked Jun 16 '14 19:06

niao


1 Answers

In your App.xaml, make sure that you have gotten rid of the StartupUri="MainWindow.xaml" property being set. Since you have overriden the OnStartup of your application and provided a custom instance of the MainWindow you shouldn't be leaving the default StartupUri property being set in the App.xaml file and WPF desperately trying to instantiate a type without a default constructor.

like image 107
Darin Dimitrov Avatar answered Oct 10 '22 00:10

Darin Dimitrov