Topics: Questions
Jul 25, 2012 at 11:08 AM



is there a possibility that my view model will be created

with the constructor which is marked with [ImportingConstructor].

I'm using Catel with a MEF Container.


Best regards, Uli

Jul 25, 2012 at 12:44 PM

Quick and dirty solution w/o dataContext parameter.

I created my own MefViewModelFactory.


using System;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using Catel.MVVM;

namespace MefViewModelFactory 
{ public class MefViewModelFactory : ViewModelFactory { private readonly CompositionContainer container; public MefViewModelFactory(CompositionContainer container) { this.container = container; } public override IViewModel CreateViewModel(Type viewModelType, object dataContext) { // get a reference to the GetExportedValue<T> method var methodInfo = container.GetType().GetMethods().First(d => d.Name == "GetExportedValue" && d.GetParameters().Length == 0); // create an array of the generic types that the GetExportedValue<T> method expects var genericTypeArray = new Type[] { viewModelType }; // add the generic types to the method methodInfo = methodInfo.MakeGenericMethod(genericTypeArray); // invoke GetExportedValue<type>() var obj = methodInfo.Invoke(container, null); // Fall back to default behavior //return base.CreateViewModel(viewModelType, dataContext); return obj as IViewModel; } } }
Jul 25, 2012 at 2:11 PM

We don't have a good feeling with both MEF and constructor injection specified by the types itself.

All view models are constructed by the ViewModelFactory. You did the right thing by overriding the right methods. Don't forget to register it in the IoC container manually.

I know that you can instantiate stuff in Unity with a unity helper so it respects the attributes you use. I bet they did the same for MEF, so why not use the right MEF helper in that method and you can consider it a "clean" approach :)

Jul 25, 2012 at 2:18 PM

So you prefer Unity?

Also in conjunction with Prism?

Jul 25, 2012 at 3:27 PM

Well, we prefer the servicelocator of Catel ;)

However, I have a better experience with Unity, I think MEF is too overengineered and makes your app slow and hard to understand for new devs. But again, this is just my opinion, the guys of MEF must think differently about this ;)