MEF插件开发案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

namespace WebApplication3
{
   
   public interface ICalculator
    {
        String Calculate(String input);
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.Composition;

namespace WebApplication3
{
    [Export(typeof(ICalculator))]
    public class MySimpleCalculator : ICalculator
    {
        public string Calculate(string input)
        {
            return "MySimpleCalculator 处理了" + input;

        }

    }


}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
using System.Reflection;

namespace WebApplication3
{
    public class ComposCLass
    {
        private CompositionContainer _container;
        [Import]
        public ICalculator calculator1{set;get;}
        public ComposCLass()
        {
            Compose();
        }

        public void Compose()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            _container = new CompositionContainer(catalog);
            try
            {
                this._container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
            }
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace WebApplication3
{
 


    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ComposCLass classp = new ComposCLass();
            //classp.Compose();
            Response.Write(classp.calculator1.Calculate("asldhcgashdcbgalshdcblasdhc"));
        }
    }
}

 

posted @ 2013-06-15 16:50  greefsong  阅读(201)  评论(0编辑  收藏  举报