在WPF应用程序中的哪里放置和配置IoC容器? [英] Where to place and configure IoC container in a WPF application?

查看:456
本文介绍了在WPF应用程序中的哪里放置和配置IoC容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个中型WPF应用程序(MVVM),该应用程序将来应该可以扩展和维护。因此,我决定使用IoC容器(在这种情况下为Unity)保持灵活性。

I am working on a middle sized WPF application (MVVM) that should be extensible and maintainable in the future. Thus I decided to use an IoC container (Unity in this case) to keep things flexible.

但是我不确定在WPF应用程序中将Unity放置和配置的位置。

However I am not sure where to place and configure Unity in a WPF application.

我想容器应该是可全局访问的,因此它应该转到Application类。但是我应该将其设置为静态属性吗?我应该在Application_Startup()事件处理程序中配置它吗?

I guess container should be accessible globally so it should probably go to Application class. But should I make it as static property? Should I configure it in Application_Startup() event handler?

例如:

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    public static UnityContainer MyUnityContainer;


    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // instantiate and configure Unity
    }
}

这样,我将能够通过静态属性从应用程序中的任何位置访问容器:

This way I will be able to access container from any place in the application via static property:

App.MyUnityContainer

我猜这是解决问题的一种方法,但是我不确定是否有针对此问题的更好的实践,特别是针对WPF应用程序。

I guess this is one way to do it but I am not sure if there are better practices for this issue, specifically for WPF apps.

推荐答案

查看组合根模式。您想要做的是在Startup事件处理程序中对其进行初始化,而忘了它在应用程序其余部分中的存在。

Have a look at the Composition Root Pattern. What you want to do is to initialize it in your Startup event handler and forget about its existence for the rest of the application.

您正在尝试实现服务定位器模式,根据许多是该问题的次等解决方案

You are trying to implement the Service Locator Pattern, which according to many is an inferior solution to this problem.

这篇关于在WPF应用程序中的哪里放置和配置IoC容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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