Search code examples
c#wpfmvvmtypesmef

Type.GetType returns null when using MEF


I'm currently using MEF for a project to import plugins, as the plugins are written in WPF they each have a view and a viewmodel. The plugins know about the viewmodel but the main shell UI will construct the view and bind the viewmodel using a convention over configuration type pattern.

I have used some code from the Build-your-own-MVVM-framework sample to do the auto view discovery:

    [ImportMany(typeof(IPlugin))]
    public IEnumerable<IPlugin> Plugins { get; set; }

   var viewTypeName = this.Plugins.First().ViewModel.GetType().AssemblyQualifiedName.Replace("Model", string.Empty);
   var viewType = Type.GetType(viewTypeName,true);

The code at the moment just gets the first plugin and takes out Model from the name, returns the view name and gets the view type so that I can construct it. So an example of what viewType would be is:

PluginTest.TestView, PluginTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

However when I call Type.GetType(viewType) I get back null, if I add the true to throw an exception I get the exception:

Could not load file or assembly 'PluginTest, Version=1.0.0.0, Culture=neutral, 
PublicKeyToken=null' or one of its dependencies. 
The system cannot find the file specified.

Even though it is already loaded using MEF.

If I do:

var types = Assembly.GetAssembly(this.Plugins.First().ViewModel.GetType()).GetTypes();

I get back a list of all the types in the assembly of the plugin, so far there is just PluginTest.TestView and PluginTest.TestViewModel

Can anyone help me with this one?

EDIT: Sorry didn't mention before, the plugins are in different assemblies to my main shell app.


Solution

  • It's probably easiest to do something like this:

    var modelType = this.Plugins.First().ViewModel.GetType();
    var viewTypeName = modelType.FullName.Replace("Model", string.Empty);
    var viewType = modelType.Assembly.GetType(viewTypeName);
    

    I'm not sure why Type.GetType isn't working for you - assembly resolution is a tricky beast - but if you know the assembly the type should be defined in anyway, I'd definitely go via Assembly.GetType instead.