编辑:马特,这确实解决了我的一些(大部分)问题,谢谢。现在唯一的问题是我如何在WPF中执行此操作?我有一个基于定制的部分断UserControl
的但在WPF没办法的事:MEF:无法在其他类中导入?
[Import]<my:SomeCustomControl>
所以级联不会在这种情况下工作。
/编辑
我有一个问题[导入]在我的项目荷兰国际集团各MEF组件。我是否必须在每个课堂上使用CompositionContainer?在下面的代码中,在方法Helper.TimesTwo()中抛出了一个空引用异常,但是当我在Program类中调用logger.Log()时,一切正常。任何帮助将不胜感激。
(这将编译并作为控制台应用程序运行)。
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
[Import]
private ILog logger { get; set; }
public void Run()
{
var catalog = new DirectoryCatalog(".");
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
logger.Log("hello");
var h = new Helper();
logger.Log(h.TimesTwo(15).ToString());
Console.ReadKey();
}
}
class Helper
{
[Import]
private IDouble doubler { get; set; }
private Helper()
{
// do I have to do all the work with CompositionContainer here again?
}
public double TimesTwo(double d)
{
return doubler.DoubleIt(d);
}
}
interface ILog
{
void Log(string message);
}
[Export(typeof(ILog))]
class MyLog : ILog
{
public void Log(string message)
{
Console.WriteLine("mylog: " + message);
}
}
interface IDouble
{
double DoubleIt(double d);
}
[Export(typeof(IDouble))]
class MyDoubler : IDouble
{
public double DoubleIt(double d)
{
return d * 2.0;
}
}
}
我想知道你是否看过这个,Glenn,因为你最近接连发布了关于MEF + WPF的推文。 :) – 2009-02-03 01:06:29