开发者

put two named instances in MEF

In Unity I would do something like this开发者_StackOverflow社区:

Container.RegisterType<MyClass>("MyNamedInstance", new ContainerControlledLifetimeManager());

Then I could put multiple instances of the same class in.

How can I do this in MEF?


It looks like named exports were added in the latest preview release (MEF 2 Preview 3) as part of MEF's Convention Model (see the "explicit wiring" section).

However, this is not yet available in .NET 4. Also, the APIs in the preview releases are subject to change.

For now, you could create two exports for the same class with different contracts by adding the name to the export's contract:

public class MyClass
{
}

public class MyClassExporter
{

   [Export("Name1", typeof(MyClass))]
   public MyClass Name1
   {
       get
       {
           return new MyClass();
       }
   }

   [Export("Name2", typeof(MyClass))]
   public MyClass Name2
   {
       get
       {
           return new MyClass();
       }
   }
}

and then you could use the same contract for imports:

[Export(typeof(IFoo))]
public class Foo : IFoo
{
   [ImportingConstructor]
   public Foo([Import("Name2", typeof(MyClass))] MyClass myClass)
   {
       ...
   }
}

Instead of using a MyClassExporter with property exports you could also put the export attributes on derived classes, which is perhaps easier to understand but doesn't work on sealed classes:

[Export("Name1", typeof(MyClass)]
public class MyClass1 : MyClass
{
}

[Export("Name2", typeof(MyClass)]
public class MyClass2 : MyClass
{
}


ExportAttribute Class

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = true, 
    Inherited = false)]
public class ExportAttribute : Attribute

It is marked for AllowMultiple = true... which means you can do the following:

[Export("MyClass1")]
[Export("MyClass2")]
[PartCreationPolicy(CreationPolicy.NonShared)] //Otherwise they'll point to the same reference.
public class MyClass : IMyClass
{
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜