MEF-导入字典

时间:2015-04-27 19:56:14

标签: c# dependency-injection mef

Iam目前正在重构一个应用程序并希望引入MEF。 Export类(Apple类)已完成并标有Export-keyword ... 在导入网站上,我目前有一个字典,初始化如下所示:

Dictionary<int, Apple> dict = new Dictionary<int, Apple>();
for(int i=0; i < 10; i++)
    dict.add(i, new Apple());

...

如何使用MEF初始化字典?

1 个答案:

答案 0 :(得分:1)

所以我认为你的问题归结为“如何确保容器产生一个对象的多个实例,而不是每次请求时都重复使用同一个对象。”嗯,这很简单 - 您只需指定CreationPolicy.NonShared

考虑IApple的示例实现:

public interface IApple { }

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IApple))]
public class Apple : IApple 
{ 
    private static int appleCounter = 0;
    private int id;

    public Apple() 
    {
        this.id = ++appleCounter;
    }

    public override string ToString()
    {
        return "Apple #" + this.id.ToString();
    }
}

以下是您可以使用它的一种方式:

class Program
{
    public static void Main(string[] args)
    {
        var catalog = new ApplicationCatalog();
        var container = new CompositionContainer(catalog);
        IDictionary<int, IApple> dict = new Dictionary<int, IApple>();
        for (int i = 0; i < 10; i++)
        {
            dict.Add(i, container.GetExportedValue<IApple>());
        }

        foreach (var pair in dict)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }
}

这里的关键代码是[PartCreationPolicy(CreationPolicy.NonShared)]。如果没有这个,就会创建唯一的Apple。当然,这并不像你希望的那样有用。这是生成一个更灵活的字典的另一种方法:

public interface IBasket
{
    IDictionary<int, IApple> GetAppleDictionary();
}

[Export(typeof(IBasket))]
public class Basket : IBasket
{
    private IDictionary<int, IApple> dict;

    [ImportingConstructor]
    public Basket([Import] CompositionContainer container)
    {
        this.dict = new Dictionary<int, IApple>();
        for (int i = 0; i < 10; i++)
        {
            this.dict.Add(i, container.GetExportedValue<IApple>());
        }
    }

    public IDictionary<int, IApple> GetAppleDictionary()
    {
        return dict;
    }
}

class Program
{
    [Import(typeof(IBasket))]
    private IBasket basket = null;

    public static void Main(string[] args)
    {
        var program = new Program();
        program.Run();
    }

    private void Run()
    {
        var catalog = new ApplicationCatalog();
        var container = CreateCompositionContainer(catalog);
        container.ComposeParts(this);
        foreach (var pair in this.basket.GetAppleDictionary())
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }

    private static CompositionContainer CreateCompositionContainer(ComposablePartCatalog catalog)
    {
        var wrappedCatalog = new AggregateCatalog(catalog, new TypeCatalog(typeof (CompositionContainer)));
        var container = new CompositionContainer(wrappedCatalog);
        container.ComposeExportedValue(container);

        return container;
    }
}

这里棘手的部分是CreateCompositionContainer。此方法可确保CompositionContainer本身可用于满足对其正在编写的对象的导入。这允许Basket直接操纵容器以生成它所需的所有苹果。

只是出于演示的目的,这里有一种方法你也可以使用[ImportMany]属性来完成类似的事情(尽管所有[Export]真的让我感到畏缩):

public interface IApple { }

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IApple))]
[Export(typeof(IApple))]
/* ..repeat N times.. */
[Export(typeof(IApple))]
public class Apple : IApple 
{ 
    private static int appleCounter = 0;
    private int id;

    public Apple() 
    {
        this.id = ++appleCounter;
    }

    public override string ToString()
    {
        return "Apple #" + this.id.ToString();
    }
}

class Program
{
    [ImportMany(typeof(IApple))]
    private IEnumerable<IApple> apples = null;

    public static void Main(string[] args)
    {
        var program = new Program();
        program.Run();
    }

    void Run()
    {
        var catalog = new AssemblyCatalog(this.GetType().Assembly);
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
        apples.Dump();
    }
}