如何在Metro风格的应用程序中获取导出的值(MEF) [英] How to get exported values (MEF) in metro style apps

查看:71
本文介绍了如何在Metro风格的应用程序中获取导出的值(MEF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认识到,MEF仅限于Metro风格的应用程序.不再有容器,那么如何获取特定的导出值,例如ILogger logger = container.GetExportedValues<ILogger>();? 是否有涵盖MEF都市版的任何教程?

I recognized, that MEF is limited for metro style apps. There is no container anymore, so how can I get specific exported values like ILogger logger = container.GetExportedValues<ILogger>();? Is the any tutorial available covering the metro version of MEF?

感谢您的帮助, 恩

推荐答案

正如我在评论中所写的那样,我不太喜欢这种方法,但这是目前为止我所拥有的最好的方法:

As I already wrote in the comment, I don't really like this approach, but it is the best what I have up to this moment:

public class CompositionContainer
{
    private readonly CompositionService _service;

    public CompositionContainer(CompositionService service)
    {
        _service = service;
    }

    public T GetExportedValue<T>()
    {
        var factoryProvider = new FactoryProvider<T>();
        _service.SatisfyImportsOnce(factoryProvider);
        return factoryProvider.Factory.CreateExport().Value;
    }

    private class FactoryProvider<T>
    {
        [Import]
        public ExportFactory<T> Factory;
    }
}

,简单的用例可能就是这样:

and the simple use-case might be this one:

class Program
{
    static void Main()
    {
        var catalog = new ApplicationCatalog();
        var container = new CompositionContainer(catalog.CreateCompositionService());
        for (int i = 0; i < 5; i++)
        {
            var dude = container.GetExportedValue<IDude>();
            Console.WriteLine(dude.Say());
        }
    }
    public interface IDude
    {
        string Say();
    }

    [Export(typeof(IDude))]
    public class Eminem : IDude
    {
        private static int _instanceNo;
        private readonly string _phrase;

        public Eminem()
        {
            _instanceNo++;
            _phrase = string.Join(" ", Enumerable.Range(0, _instanceNo)
                .Select(_ => "yo!"));
        }

        public string Say()
        {
            return _phrase;
        }
    }
}

此刻我不在乎性能,但是我想稍后我将添加工厂提供程序或工厂的缓存

I don't care about performance at this moment, but I guess I'll add caching of factory providers or factories later

这篇关于如何在Metro风格的应用程序中获取导出的值(MEF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆