MEF Imported property is null

Topics: Prism v4 - WPF 4
Jan 30, 2014 at 9:59 PM
Not sure if this is a Prism or .NET Framework question, hopefully someone may enlighten me anyway:

I have a wpf application (.net 4.5) which used Prism (4.1) and MEF.
A MEF container is configured in the Bootstrapper (derived from MEFBootstrapper).
MainView (Shell) has no ViewModel, but a Region is defined.

A Module (decorated with ModuleExport) is initialized and the Region and its ViewModel is "resolved" by Region.RequestNavigate(string regionName, string ViewModelExport).

The region View imports the ViewModel etc. and everything works fine.
Now, in the ViewModel I decorate a property with Import and the type (public class with default constructor) is decorated with Export.

All the types mentioned are defined (currently) in the same assembly which is used to make an AssemblyCatalog etc. in the Bootstrapper.

The imported property of the ViewModel is always null and I don't understand why.
Jan 31, 2014 at 1:13 PM
Hi Eager,

It would be helpful if you could provide us with a small sample solution which would show the problem you are facing. Therefore, we would be able to give you better support for this scenario.

However, as a workaround, you would be able to import the property to the ViewModel by passing it as an argument on the constructor. You would need to decorate the ViewModel constructor with "[ImportConstructor]", in order to get the container resolve every constructor parameter.


Gabriel Ostrowsky
Marked as answer by Eager2008 on 1/31/2014 at 7:03 AM
Jan 31, 2014 at 2:03 PM
Hi and thanks
Meanwhile I realized that an imported property is still null (or rather it's type's default value) during the objects construction.
I changed to ImportConstructor, exactly as you mentioned and now it works :)

I think I can understand that it is difficult/impossible for MEF to set the property during construction, but prior to user code, at least with reflection.
However, if possible, it would be nice if this "limitation" could be removed...