Skip to main content
 首页 » 编程设计

c#之MEF : How can I import a class which has a constructor marked with the ImportingConstructorFlag

2024年02月24日23cloudgamer

我的问题标题听起来有点难 - 抱歉。我是 MEF 的新手 :-)。

我的场景:

public class MainClass 
{ 
  [ImportMany(typeof(ITest))] 
  private List<ITest> Tests { get; set; } 
 
  public MainClass() 
  { 
    Init(); 
  } 
 
  private void Init() 
  { 
     DirectoryCatalog catalog = new DirectoryCatalog(@"./"); 
     CompositionContainer container = new CompositionContainer(catalog); 
     container.ComposeParts(this); 
  } 
} 
 
 
 
[Export("BirthdayJob")] 
[Export(typeof(ITest))] 
public partial class BirthdayTest : ITest 
{ 
  [ImportingConstructor] 
  public BirthdayUserControl(IParameter parameter) 
  { 
     InitializeComponent(); 
     this.Parameter = jobParameter; 
  } 
 
   public IParameter Parameter { get; set; } 
} 
 
[Export(typeof(IParameter))] 
[Export("BirthdayParameter")] 
public class BirthdayJobParameter : IParameter 
{ 
   public override string ToString() 
   { 
       return "Birthday Remember"; 
   } 
} 
 
 
public interface IParameter : IMefInterface 
{ 
 
} 
 
public interface IMefInterface 
{ 
 
} 

在测试的通用列表中,我应该拥有所有可能的 ITest 对象以及关联的 IParameter 对象。不幸的是,通用列表中没有任何项目。

你能帮忙吗?我做错了什么?

提前致谢。

问候,亲

//编辑

所以我有一个可编译的类来解决我的问题:

using System; 
using System.ComponentModel.Composition; 
using System.ComponentModel.Composition.Hosting; 
 
namespace ObjectContracts 
{ 
    public class Program 
    { 
        static void Main(string[] args) 
        { 
            var container = new CompositionContainer(new TypeCatalog(typeof (IFoo), typeof (Bar), typeof(Foo))); 
            var bar = container.GetExportedValue<Bar>(); 
            Console.WriteLine(bar.Foo.Message); 
            Console.ReadLine(); 
 
        } 
 
    } 
 
    [InheritedExport] 
    public interface IFoo 
    { 
        string Message { get; set; } 
    } 
 
    [Export] 
    public class Bar 
    { 
        [ImportingConstructor] 
        public Bar([Import("Foo")]IFoo foo) 
        { 
            this.Foo = foo; 
        } 
 
        public IFoo Foo { get; set;} 
    } 
 
    [Export("Foo")] 
    public class Foo : IFoo 
    { 
        public Foo() 
        { 
            Message = ":-)"; 
        } 
        public string Message { get; set; } 
    } 
} 

我做错了什么?请帮助我:-)

问候,帕特里克

请您参考如下方法:

要点是,如果您在导出中使用契约(Contract)(在您的例子中为“BirthdayJob”),您也需要在导入中指定它。像这样:

[Export("BirthdayJob",typeof(ITest))] 
public partial class BirthdayTest : ITest 
{ 
  // class definition 
} 

还有你的导入:

public class MainClass 
{ 
  [ImportMany("BirthdayJob",typeof(ITest))] 
  private List<ITest> Tests { get; set; } 
 
  // class definition 
} 

契约的伟大之处在于它们允许您对特定类型的某些对象的实例进行分组,并过滤​​掉任何不需要的特定类型对象的实例。

MEF 是最酷的!

[Export("PeopleLivingInEdmontonAlbertaCanada",typeof(IPerson))] 
public Person KevinParkinson { get; set; }