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;
        }
    }
复制代码

} 

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

posted @   qiang.xu  阅读(1263)  评论(7编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示