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

后端 未结 3 476
星月不相逢
星月不相逢 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: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.

提交回复
热议问题