MEF初体验之十一:查询组合容器

查询组合容器

组合容器暴露了几个get exports的重载方法和导出对象和对象集合。
你需要注意下面的行为:

  • 当请求单个对象实例时,如果未发现导出,一个异常将被抛出
  • 当请求单个对象实例时,如果发现超过一个,一个异常将被抛出

GetExportedValue方法

在下面的代码片段中,我们请求一个Root(契约)实例的对象

var container = new CompositionContainer(new AssemblyCatalog(typeof(Program).Assembly));
Root partInstance = container.GetExportedValue<Root>();


如果你在一个不同的契约名字下有一个导出,你将需要使用一个不同的重载:

[Export("my_contract_name")]
public class Root
{
}

var container = new CompositionContainer(new AssemblyCatalog(typeof(Program).Assembly));
Root partInstance = container.GetExportedValue<Root>("my_contract_name");

GetExport方法

GetExport方法检索Export的一个Lazy的实例引用。访问export的Value属性将促使导出实例被创建。导出值的连续调用将返回相同的对象,而不管部件是否有一个共享/非共享的生命周期。

Lazy<Root> export = container.GetExport<Root>();
var root = export.Value; //create the instance.

GetExportedValueOrDefault方法

GetExportedValueOrDefault方法恰好GetExportedValue方法一样工作,不同的是在没有匹配情况下它不会抛出一个异常。

var root = container.GetExportedValueOrDefault<Root>(); // may return null

最后仍然举个例子:

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QueryingCompositionContainer
{
    class Program
    {
        [Import]
        public IMessageSender Sender { get; set; }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Run();
            Console.ReadKey();
        }
        void Run()
        {
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);

            IMessageSender s = container.GetExportedValue<IMessageSender>();
            Console.WriteLine(s == Sender);
            IMessageSender s2 = container.GetExportedValueOrDefault<EmailSender>();
            if(s2 == null)
                Console.WriteLine("Exported EmailSender is null");
            Lazy<IMessageSender> s3 = container.GetExport<IMessageSender>();
            var s3_1 = s3.Value;
            var s3_2 = s3.Value;
            Console.WriteLine(s3_1 == s3_2);//True,Lazy<T>特性
            Console.WriteLine(s3_1 == Sender);
        }
    }
    interface IMessageSender
    {
        void Send(string msg);
    }
    [Export(typeof(IMessageSender))]
    class EmailSender : IMessageSender
    {
        public void Send(string msg)
        {
            Console.WriteLine("Email sent:" + msg);
        }
    }

}
复制代码

输出如图:

posted @   jello chen  阅读(859)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)

点击右上角即可分享
微信分享提示