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

后端 未结 3 457
星月不相逢
星月不相逢 2020-12-29 07:58

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) t

相关标签:
3条回答
  • 2020-12-29 08:15

    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.

    0 讨论(0)
  • 2020-12-29 08:19

    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.

    0 讨论(0)
  • 2020-12-29 08:22

    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.

    0 讨论(0)
提交回复
热议问题