MEF的asp.net Hello World程序
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;
}
}
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. 代码下载
如果您觉得不错,欢迎扫码支持下。
作者:许强1. 本博客中的文章均是个人在学习和项目开发中总结。其中难免存在不足之处 ,欢迎留言指正。 2. 本文版权归作者和博客园共有,转载时,请保留本文链接。