我尝试了以下非常好的教程https://www.eidias.com/blog/2013/7/26/plugins-in-wpf-mvvm-with-mef#cm-249迁移到 MEF2 但由于某种原因组件未显示在目录中。从 MEF2 我想使用 API 配置(RegistrationBuilder 类)(这里是一个例子:https ://stefanhenneken.wordpress.com/2013/01/21/mef-teil-11-neuerungen-unter-net-4-5/ ),也许有人知道如何将 MEF2 正确应用于本教程。非常感谢你。
在 MainViewModel.cs 我还不知道如何将导入集成到RegistrationBuilder
.Can 你检查其余的代码?谢谢。
namespace WPF_MEF_App
{
public class MainWindowModel : NotifyModelBase
{
public ICommand ImportPluginCommand { get; protected set; }
private IView PluginViewVar;
[Import(typeof(IView), AllowRecomposition = true, AllowDefault = true)]
public IView PluginView
{
get { return PluginViewVar; }
set{ PluginViewVar = value; NotifyChangedThis();}
}
[ImportMany(typeof(IView), AllowRecomposition = true)]
public IEnumerable<Lazy<IView>> Plugins;
private AggregateCatalog catalog;
private CompositionContainer container;
public MainWindowModel()
{
ImportPluginCommand = new DelegateCommand(ImportPluginExecute);
RegistrationBuilder builder = new RegistrationBuilder();
builder.ForType<PluginSecondScreen>()
.Export<IView>(eb =>
{
eb.AddMetadata("Name", "PluginSecond");
})
.SetCreationPolicy(CreationPolicy.Any);
//.ImportProperties(pi => pi.Name == "IView",
// (pi, ib) => ib.AllowRecomposition());
builder.ForType<CalculatorScreen>()
.Export<IView>(eb =>
{
eb.AddMetadata("Name", "CalculatorScreen");
})
.SetCreationPolicy(CreationPolicy.Any);
//.ImportProperties(pi => pi.Name == "IView",
// (pi, ib) => ib.AllowRecomposition());
catalog = new AggregateCatalog();
string pluginsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
catalog.Catalogs.Add(new DirectoryCatalog(pluginsPath, "Plugin*.dll"));
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly(), builder));
//also we add to a search path a subdirectory plugins
pluginsPath = Path.Combine(pluginsPath, "plugins");
if (!Directory.Exists(pluginsPath))
Directory.CreateDirectory(pluginsPath);
catalog.Catalogs.Add(new DirectoryCatalog(pluginsPath, "Plugin*.dll"));
//Create the CompositionContainer with the parts in the catalog.
container = new CompositionContainer(catalog);
}
private void ImportPluginExecute()
{
//refresh catalog for any changes in plugins
//catalog.Refresh();
//Fill the imports of this object
//finds imports and fills in all preperties decorated
//with Import attribute in this instance
container.ComposeParts(this);
//another option
//container.SatisfyImportsOnce(this);
}
}
}