MEF 松耦合

时间:2024-11-09 10:34:56

MEF天生就有解耦合的特性,虽然它不是为解耦而生,而主要是为插件类应用的开发而设计。如果主要是为了解除耦合的话可以使用IoC,Unity等。

Unity 微软的IOC

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace ConsoleApplication3
{
    class Program
    {
        [Import]
        public IBookService Service { get; set; }

        static void Main(string[] args)
        {
            Program pro = new Program();
            pro.Compose();
            if (pro.Service != null)
            {
                Console.WriteLine(pro.Service.GetBookName());
            }
            else
            {
                Console.WriteLine("null");
            }
            Console.Read();
        }

        private void Compose()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            CompositionContainer container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }
    }
    public interface IBookService
    {
        string BookName { get; set; }
        string GetBookName();
    }

    [Export(typeof(IBookService))]
    public class MusicBook : IBookService
    {
        public string BookName { get; set; }

        public string GetBookName()
        {
            return "MusicBook";
        }
    }
}

http://www.tuicool.com/articles/jmqyuuM

http://blog.****.net/jiangzhanchang/article/details/21173861