csharp MEF基础知识

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp MEF基础知识相关的知识,希望对你有一定的参考价值。

using System.ComponentModel.Composition;
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace MefProject
{
    class Program
    {
        [Export] private string OriginalMessage = "My Message";
        [Import] private string Message;
        
        static void Main(string[] args)
        {
            var p = new Program();
            p.Compose();
        }

        private void Compose()
        {
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
            
            // Export: OriginalMessage >> Import: Message
            Console.WriteLine(Message);
        }
    }
}
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace SeparatingExports
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Composing MEF from another class");
            var loader = new Loader();
            loader.GetCount();
        }
    }

    public class Loader
    {
        [Import] public MefExport MefExportClass;
        public Loader()
        {
            var catalog = new AssemblyCatalog(typeof(MefExport).Assembly);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        public void GetCount()
        {
            Console.WriteLine(MefExportClass.MyCount);
            Console.WriteLine(MefExportClass.UpdateCount());
        }
    }

    [Export]
    public class MefExport
    {
        public int MyCount { get; set; }

        public MefExport()
        {
            MyCount = 2;
        }

        public int UpdateCount()
        {
            MyCount++;
            return MyCount;
        }
    }
}

以上是关于csharp MEF基础知识的主要内容,如果未能解决你的问题,请参考以下文章

csharp MEF属性ベースのサンプル

C#可扩展编程之MEF:MEF高级进阶

MEF 基础简介 三

C#可扩展编程之MEF学习笔记:MEF的导出(Export)和导入(Import)

C# MEF入门讲解

C#可扩展编程之MEF:见证奇迹的时刻