Hello! My application is pretty complex, so even simplified example would be complex enough. So I'll try to point some its fundamentals and the problem itself.
It is an MDI application. MDI is of custom implementation since there is no native MDI in WPF. The problem is in main container window. It is called Shell and as it is an MVVM app, it consists of ShellView and ShellViewModel classes respectively. I register and resolve them through Unity:
shellViewModel = ServiceLocator.Instance.Resolve<IShellViewModel>();
shellView = ServiceLocator.Instance.Resolve<IShellView>();
shellView.DataContext = shellViewModel;
Assume, in ShellViewModel, I have some property of type ObservableCollection and a private field for it. So when child window for Shell is created particular event is raised and ShellViewModel handles it. In this handler I query this private field:
this.windowsItem = this.menuActioned.Where(item => item.ID == -1).SingleOrDefault();
The problem itself: if I'm resolving viewmodel and then view as it is in first code block - all goes fine, but if it is happenning vice versa, i.e:
shellView = ServiceLocator.Instance.Resolve<IShellView>();
shellViewModel = ServiceLocator.Instance.Resolve<IShellViewModel>();
shellView.DataContext = shellViewModel;
I get null value of this.menuActioned in event handler! Which leads to Value Cannot Be Null exception of Where operator. I've just noticed that any field of ShellViewModel class is also null in this time! There is some interesting thing - if I add a breakepoint right before this statement and in Whatch section add "this" watch variable - this forces to class fields reevaluation and they get real values as they should be!
Concluding - we have some value in field, which becomes null after event is fired.
If I use usual instantiation, not through Unity, I have no such problem, regardless of ViewModel and View instantiation order:
shellView = new ShellView();
shellViewModel = new ShellViewModel();
shellView.DataContext = shellViewModel;
This problem occured while moving app to Unity DI and Service Locator pattern.