Getting container in View Model

Jan 28, 2014 at 6:42 PM
Edited Jan 28, 2014 at 6:48 PM
I have a view that defines a view model in xaml:
        <VM:MainMenuViewModel />
Then my VM:
   public class MainMenuViewModel
        private readonly IUnityContainer container;

        public MainMenuViewModel(IUnityContainer _container)
            container = _container; 
I get an error saying that no accessible constructor exists when the view runs because it isn't injecting the IUnityContainer. What is the "proper" way to access the container from a view model? Thanks.
Jan 29, 2014 at 12:39 PM
Hello Mathius,

You may find this similar question already answered in the following Stack Overflow post:

You would properly get the container from the ViewModel constructor by previously resolving the ViewModel instance from the container.

I hope this helps, Regards.

Gabriel Ostrowsky
Jan 29, 2014 at 2:41 PM
I guess I am confused. If I am creating my view model in xaml, how would I properly "instantiate" this view model using the container if I can't get access to the container? I just can't see how the workflow is supposed to work with containers and view models. I tried "BuildUp" with method injection, and the container gets injected in on new VM(), but then it is lost because a new VM is created when the xaml runs(as it creates a new VM). Is there any small example someone could give about a simple way to accomplish this? Am I not supposed to create the VM in xaml with Unity? Thanks.
Jan 29, 2014 at 3:30 PM
I am using the Common Service Locator library, which allows you to use a static singleton class to access your global container. Works really well. Thanks!