使用MEF时Type.GetType返回null [英] Type.GetType returns null when using MEF

查看:110
本文介绍了使用MEF时Type.GetType返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将MEF用于导入插件的项目,因为这些插件是用WPF编写的,因此每个插件都有一个视图和一个视图模型.插件知道ViewModel,但主外壳UI会使用配置类型模式的约定构造视图并绑定ViewModel.

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.

我已经使用Build-your-own-MVVM-framework示例中的一些代码来进行自动视图发现:

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);

此刻的代码只是获取第一个插件,并从名称中取出Model,返回视图名称并获取视图类型,以便我可以构造它.因此,viewType的示例是:

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

但是,当我呼叫Type.GetType(viewType)时,我返回null,如果我添加true引发异常,则会得到异常:

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.

即使已经使用MEF加载了它.

Even though it is already loaded using MEF.

如果我这样做:

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

我返回了插件程序集中所有类型的列表,到目前为止,只有PluginTest.TestViewPluginTest.TestViewModel

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

有人可以帮我吗?

对不起,之前没有提到,这些插件与我的主Shell应用程序位于不同的程序集中.

推荐答案

做这样的事情可能最简单:

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);

我不确定为什么Type.GetType对您不起作用-程序集解析是一个棘手的问题-但如果您知道该程序集无论如何都应该定义类型,我肯定会通过Assembly.GetType

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.

这篇关于使用MEF时Type.GetType返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆