tags:

views:

49

answers:

2

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.

+1  A: 

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.

Jon Skeet
It still seems to return null hmmm..
Nathan W
@Nathan: So what is `viewTypeName` when you try the above code?
Jon Skeet
ahh no sorry, it works :) Did you always have modelType.FullName there I swear it was modelType.Name which is why my code didn't work. Thanks.
Nathan W
@Nathan: I had `Name` very briefly - but I edited it within about 30 seconds of posting that...
Jon Skeet
and I was just to quick on the ctl+c, never mind it's working perfectly now.
Nathan W
A: 

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

Daniel Plaisted