Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetType returns null when using MEF

Tags:

c#

types

mvvm

wpf

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.

like image 462
Nathan W Avatar asked Sep 30 '26 09:09

Nathan W


2 Answers

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.

like image 141
Jon Skeet Avatar answered Oct 01 '26 23:10

Jon Skeet


The assembly was probably loaded in the Load-From context, and Type.GetType() doesn't work with assemblies loaded in that context. MEF tries to load assemblies in the default context, but if that doesn't work it loads them in the Load-From context.

More about assembly load contexts in .NET

like image 45
Daniel Plaisted Avatar answered Oct 01 '26 22:10

Daniel Plaisted



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!