编辑:Matt,这确实解决了我大部分问题,谢谢。现在唯一的问题是如何在WPF中实现这个?我有一个基于UserControl
的自定义部件,但在WPF中没有办法执行:
[Import]<my:SomeCustomControl>
所以在这种情况下,级联不起作用。
/编辑
我在我的项目中[Import]导入各种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;
}
}
}