1.瞭解MEF
2. 簡單的demo
3. 代碼下載
1. 瞭解MEF
mef是codeplex上的開源項目,地址:http://mef.codeplex.com/,工程目的: simplifying the design of extensible applications and components.
2. 簡單demo
2.1 建立asp.net web application,添加 System.ComponentModel.Composition的應用。
2.2 添加一個web form頁面aspnetMEFBasic.aspx,後台代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MEF
{
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
public partial class aspnetMEFBasic : System.Web.UI.Page
{
[Import]
Class1 c1;
protected void Page_Load(object sender, EventArgs e)
{
//Step 1:
//Find the assembly (.dll) that has the stuff
// we need (i.e. [Export]ed stuff) and put it in our catalog
DirectoryCatalog catalog =
new DirectoryCatalog(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"));
//Step 2:
//To do anything with the stuff in the catalog, we need to
// put into a container (Which has methods to do the magic stuff)
CompositionContainer container =
new CompositionContainer(catalog);
//Step 3:
//Now lets do the magic bit - Wiring everything up
container.ComposeParts(this);
//Step4:
//Lets see if it works
div1.InnerText = c1.s1;
}
}
}
2.3 添加類Class1,代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MEF
{
using System.ComponentModel.Composition;
[Export]
public class Class1
{
public string s1 = "Hello World";
}
}
2.4 運行aspnetMEFBasic.aspx網頁,結果如下:
3. 代碼下載
/Files/xuqiang/MEF.rar