MEF生命周期

MEF生命周期
MEF生命周期分为三种:
ANY:MEF根据自己的需要设置是否共享
Shared:共享部件,可以在多个MEF组合容器中使用
NoShared:不共享部件,每次使用都需要创建实例
在MEF的实现通过PartCreationPolicyAttribute特性实现对部件的生命周期配置。

使用举例:

///导出
using System.ComponentModel.Composition;


namespace MEF0001
{
    public interface IMetadata
    {
        string Name { get; }
    }

    public interface ILog
    {
        string Write();
    }

    [PartCreationPolicy(CreationPolicy.Any)]
    [ExportMetadata("Name", "DBLOG")]
    [Export(typeof(ILog))]
    public class DBLog : ILog
    {

        public string Write()
        {
            return "DBLOG";
        }
    }

    [PartCreationPolicy(CreationPolicy.Shared)]
    [ExportMetadata("Name", "TXTLOG")]
    [Export(typeof(ILog))]
    public class TXTLog : ILog
    {

        public string Write()
        {
            return "TXTLog";
        }
    }

    [PartCreationPolicy(CreationPolicy.NonShared)]
    [ExportMetadata("Name", "XMLLOG")]
    [Export(typeof(ILog))]
    public class XMLLog : ILog
    {

        public string Write()
        {
            return "XMLLog";
        }
    }
}

///导入
       #region 元数据导入 和 MEF生命周期
        [ImportMany(typeof(ILog),RequiredCreationPolicy=CreationPolicy.NonShared)]
        public Lazy[] Logs { get; set; }

        public string Run()
        {
            string value = string.Empty;
            foreach (var log in Logs)
            {
                value += log.Metadata.Name + "\n";
            }
            return value;
        }


        #endregion


示例代码(该示例代码包括延迟加载和元数据加载及MEF生命周期):http://files.cnblogs.com/Clivia/MEF001.rar

转载于:https://www.cnblogs.com/Clivia/archive/2010/11/12/MEF11.html

你可能感兴趣的:(MEF生命周期)