WPF 和 Unity - 在类型上找不到匹配的构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24251244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF and Unity - No matching constructor found on type
提问by niao
I want to use Unity in my WPF application using VS2012, I defined unity container as follows:
我想在使用 VS2012 的 WPF 应用程序中使用 Unity,我定义了统一容器如下:
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'.
PresentationFramework.dll 中发生类型为“System.Windows.Markup.XamlParseException”的未处理异常
附加信息:'在类型'WPFClient.MainWindow'上找不到匹配的构造函数。您可以使用 Arguments 或 FactoryMethod 指令来构造此类型。行号“3”和行位置“9”。
What am I doing wrong?
我究竟做错了什么?
回答by Darin Dimitrov
In your App.xaml, make sure that you have gotten rid of the StartupUri="MainWindow.xaml"property being set. Since you have overriden the OnStartupof your application and provided a custom instance of the MainWindowyou shouldn't be leaving the default StartupUriproperty being set in the App.xaml file and WPF desperately trying to instantiate a type without a default constructor.
在您的 中App.xaml,确保您已经摆脱了StartupUri="MainWindow.xaml"正在设置的属性。由于您已经覆盖了OnStartup应用程序的 并提供了 的自定义实例,因此MainWindow您不应保留StartupUri在 App.xaml 文件中设置的默认属性,并且 WPF 会拼命尝试在没有默认构造函数的情况下实例化类型。
回答by CoderRoller
To complement the excellent answer, after deleting the startup URI don't forget to call the startup method within your App.xaml declaration:
为了补充出色的答案,删除启动 URI 后不要忘记在 App.xaml 声明中调用启动方法:
<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();
}
}

