Where to place and configure IoC container in a WPF application?

梦想的初衷 提交于 2019-11-30 08:42:33

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.

Let me post what I've concluded and hopefully it'll help people out. Correct if there's anything wrong! :P

I guess we'd be looking into something like this:

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        UnityContainer myUnityContainer = new UnityContainer();
        //make sure your container is configured
        myUnityContainer.RegisterType<ISomeDependency, SomeDependencyImplementation>();
        myUnityContainer.RegisterType<IMainWindow, MainWindow>();

        myUnityContainer.Resolve<IMainWindow>().Show();
    }
}

public partial class MainWindow : Window, IMainWindow
{
    private ISomeDependency _someDependency;

    public MainWindow(ISomeDependency someDependency)
    {
        _someDependency = someDependency;
    }
}

Note there are no globals or singletons, the container survives as long as MainWindow does and all dependencies behind this point of entry further into the composition graph are automagically resolved as long as the container knows about them.

As per new version of Unity container, we have to register it's own instance as well to get it in view models via constructor injection.

App.xaml.cs file:

protected override void OnStartup(StartupEventArgs e)
{
       var unityIoC = new UnityContainer();
       unityIoC.RegisterTypes(AllClasses.FromAssembliesInBasePath(), WithMappings.FromMatchingInterface, WithName.Default);
       unityIoC.RegisterInstance(typeof(IUnityContainer), unityIoC);
}

View Model class

[InjectionConstructor]
public MyViewModel(IUnityContainer container)
{
}

Now unity container would be available for us in view model and can be used to resolve.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!