窗口依赖注入 [英] Window dependency injection

查看:92
本文介绍了窗口依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WPF应用程序中使用Unity依赖项注入。我的窗口抛出System.Windows.Markup.XamlParseException:

I want to use Unity dependency injection in WPF application. My Window throw System.Windows.Markup.XamlParseException:


对于类型MainWindow,找不到默认构造函数。

"For type MainWindow found no default constructor".

这是我的代码:

App.xaml。 cs:

IUnityContainer container = new UnityContainer();
container.RegisterType<MainWindow>();
container.RegisterType<IService, MyService>();
container.RegisterType<IRepository, MyRepository>();
container.Resolve<MainWindow>().Show();

MainWindow.xaml.cs:

public MainWindow(IService service)
{
     InitializeComponent();
     service.Test();
}


推荐答案

您始终需要为了使WPF应用程序正常工作,视图的默认构造函数。

You always need to have a default constructor for your view in order for your WPF application to work properly.

public MainWindow()
{
     InitializeComponent();
}

然后定义这样的参数化构造函数:

and then define the parameterized constructor like this :

public MainWindow(IService service) : this()
{
     service.Test();
}

这篇关于窗口依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆