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

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


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.