WPF and Unity - No matching constructor found on type
Asked Answered
B

2

11

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?

Brooke answered 16/6, 2014 at 19:58 Comment(2)
In which file/location did you place the code in which you are registering the dependencies in the container and instantiating the main window?Biology
protected override void OnStartup(StartupEventArgs e) in App.xaml.csBrooke
B
31

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.

Biology answered 16/6, 2014 at 20:26 Comment(2)
I just spent a good deal of time wrestling with this bug - Expression Studio 4 tries to be clever and re-inserts the StartupUri based on the last control created.Rosaleerosaleen
Back here for the second time. I'd give you another up-vote if I could. Cheers.Ahead
S
0

To complement the excellent answer, after deleting the startup URI don't forget to call the startup method within your App.xaml declaration:

<Application x:Class="Test.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Test.App"
             Startup="Application_Startup">
    <Application.Resources>         
    </Application.Resources>
</Application>

public partial class App : Application
    {
        public IContainer container { get; private set; }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var dependencyConfigurator = new DependencyConfig();
            container = dependencyConfigurator.Configure();
            container.Resolve<WindowClassName>();
            MainWindow.Show();
        }        
    }
Selfimportant answered 3/10, 2019 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.