wpfmvvmimportconstructormef

How to call the ViewModel in the Command properly with the Mef container?


I want to call the "MainViewModel" in my Command and i wanted to ask how do i call it correctly.

This is my Mef-Container class:

public static class MefComponent
    {

        private static CompositionContainer compositionContainer;

        public static T GetImplementationOf<T>()
        {
            try
            {
                return CompositionContainer.GetExportedValue<T>();
            }
            catch (ImportCardinalityMismatchException)
            {
                throw new ImportCardinalityMismatchException();
            }
            catch (Exception)
            {
                throw new Exception();
            }
        }

        public static void InitCompositionContainer(object component)
        {
            try
            {
                AggregateCatalog aggregateCatalog = new AggregateCatalog();
                aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));
                compositionContainer = new CompositionContainer(aggregateCatalog);
                compositionContainer.ComposeParts(component);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static CompositionContainer CompositionContainer
        {
            get
            {
                return compositionContainer;
            }
        }
    }

I wanted to call the ViewModel with the "ImportingConstructor" attribute in the constructor in my command class but that didnt worked well. (Im calling the Command in the constructor in my view model like: CommandXY = MefComponent.GetImplementationOf();)

How can I call the ViewModel in other ways?

Thanks already for the answers!!!!

When i called the viewmodel I got an internal error in my exception message.

My thought about this is following: When im calling the command through the mef container, the constructor gets called in there, i want the Viewmodel, an it goes back to the viewmodel constructor, it wants to call the command constructor and so on...


Solution

  • Solved the problem.

    I had to load the class lazy!