现在的位置: 首页 > 综合 > 正文

MEF的asp.net Hello World程序

2011年04月21日 ⁄ 综合 ⁄ 共 1724字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.