PRISM + MEF - Import& ImportMany

时间:2011-03-02 18:40:03

标签: c# dependency-injection mef

FooService.cs

public interface IFooService
{
    int Foo();
}

[Export("Foo1", typeof(IFooService))]
public class Foo1 : IFooService
{
    public int Foo() { return 1; }
}


[Export("Foo2", typeof(IFooService))]
public class Foo2 : IFooService
{
    public int Foo() { return 2; }
}

FooViewModel.cs

public class FooViewModel : NotificationObject
{
    [ImportMany(typeof(IFooService))]
    public IEnumerable<IFooService> FooServices { get; private set; }

    [Import("Foo1")]
    public IFooService FirstFoo { get; private set; }
}

<小时/> 单个导入有效,因为我有一个命名合同,但多重导入没有。如果我更改导出属性并删除指定的合同,则多重导入有效,但单个导入不起作用。我怎样才能让两者同时工作?

1 个答案:

答案 0 :(得分:3)

您可以在类上添加多个导出属性:

[Export(typeof(IFooService))]
[Export("Foo1", typeof(IFooService))]
public class Foo1 : IFooService
{
    public int Foo() { return 1; }
}

[Export(typeof(IFooService))]
[Export("Foo2", typeof(IFooService))]
public class Foo2 : IFooService
{
    public int Foo() { return 2; }
}