在下面的代码中,我尝试使用MEF将导入与匹配的导出相匹配。 TestMEFClass具有导入和导出,它们共享匹配的合同名称。导出应该在每次调用时递增一个计数器。
当我将导出打印到控制台时,它没有增加计数器。有人可以指出我的错误吗?
非常感谢,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MEFConsoleTest {
public class TestMEFClass {
/// <summary>
/// This counter should increment everytime the getter in the ExportString property gets called.
/// </summary>
private int counter = 0;
[Export("Contract_Name")]
public string ExportString {
get {
return "ExportString has been called " + counter++.ToString();
}
}
[Import("Contract_Name")]
public string ImportString { get; set; }
/// <summary>
/// Default Constructor.
/// Make a catalog from this assembly, add it to the container and compose the parts.
/// </summary>
public TestMEFClass() {
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
class Program {
static void Main(string[] args) {
TestMEFClass testClass = new TestMEFClass();
Console.WriteLine(testClass.ImportString);
Console.WriteLine(testClass.ImportString);
Console.ReadLine();
}
}
答案 0 :(得分:0)
由于我无法解释的原因,此时我无法获得MEF和属性导入/导出以处理可变属性。但是,使用函数可以解决问题。我希望这段代码可以帮助别人。
谢谢,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MEFConsoleTest {
public class TestMEFClass {
/// <summary>
/// This counter should increment everytime the getter in the ExportString property gets called.
/// </summary>
private int counter = 0;
[Export("Contract_Name")]
string ExportMethod() {
return ExportString;
}
public string ExportString {
get {
return "ExportString has been called " + counter++.ToString();
}
}
[Import("Contract_Name")]
Func<string> ImportMethod;
public string ImportString { get { return ImportMethod(); } }
/// <summary>
/// Default Constructor.
/// Make a catalog from this assembly, add it to the container and compose the parts.
/// </summary>
public TestMEFClass() {
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
class Program {
static void Main(string[] args) {
TestMEFClass testClass = new TestMEFClass();
for (int x = 0; x < 10; x++) {
Console.WriteLine(testClass.ImportString);
}
Console.ReadLine();
}
}
}