mef是 managed extensibility framework簡稱,在計算機的世界什麼都會加一個簡稱,這我們大家已經司空見慣了。從名字我們可以知道它是一個用于管理的可擴充性架構。這是和el不同的另一種ioc方式;
mef 為我們提供了一種運作時的擴充,具體應用在對象的執行個體化。它有目錄(assemblycatalog)和容器(compositioncontainer)組成,他有輸入輸出(exports和imports)中繼資料标記,在對象執行個體化的時候會自動比對這個契約。
下面是官方的一個展示圖:
由compositioncontainer來管理我們的多個可組合部件。
下面我們來一個簡單的示例來初步了解mef:
控制台程式:
代碼
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.componentmodel.composition;//添加引用
namespace meftest
{
public interface ilog
{
void write(string message);
}
[system.componentmodel.composition.export(typeof(ilog))]
public class consolelog:ilog
public void write(string message)
{
console.writeline("hello:"+message);
}
class program
[system.componentmodel.composition.import(typeof(ilog))]
public ilog log;
static void main(string[] args)
program pro = new program();
pro.init();
pro.log.write("test");
console.read();
}
public void init()
var assem = system.reflection.assembly.getexecutingassembly();//目前程式集
var assemcat = new system.componentmodel.composition.hosting.assemblycatalog(assem);//建構目錄
var container = new system.componentmodel.composition.hosting.compositioncontainer(assemcat);//建構容器
container.composeparts(this);//這是一個system.componentmodel.composition.attributedmodelservices 的擴充方法。
}
輸出為:
hello:test
exportattribute 定義如下:
[attributeusage(attributetargets.class | attributetargets.method | attributetargets.property | attributetargets.field, allowmultiple = true, inherited = false)]
public class exportattribute : attribute
[targetedpatchingoptout("performance critical to inline this type of method across ngen image boundaries")]
public exportattribute(type contracttype);
public exportattribute(string contractname, type contracttype);
public string contractname { get; }
public type contracttype { get; }
從他的定義我們可以知道他可以運用于我們的類、方法、屬性、字段,并且可以多繼承,但是不存在從父類的繼承特性。
他有三種不同的标記方式方式.在mef中這裡标記為可以導出,即注入到import。
importattribute 定義:
[attributeusage(attributetargets.property | attributetargets.field | attributetargets.parameter, allowmultiple = false, inherited = false)]
public class importattribute : attribute, iattributedimport
[targetedpatchingoptout("performance critical to inline this type of method across ngen image boundaries")]
public importattribute();
public importattribute(string contractname);
public importattribute(type contracttype);
public importattribute(string contractname, type contracttype);
public bool allowdefault { get; set; }
public bool allowrecomposition { get; set; }
public string contractname { get; }
public type contracttype { get; }
public creationpolicy requiredcreationpolicy { get; set; }
}
同上export,這裡标記為可被export注入的接口點。
今天就寫到這裡了,希望大家多多指教,大家一起共同進步。