IOCContainer文件: Global.asax: 使用: ...
IOCContainer文件:
public class IOCContainer { /// <summary> /// 容器 /// </summary> public static CompositionContainer Container { get; private set; } private static IOCContainer instance = new IOCContainer(); private IOCContainer() { if (Container == null) { try { //獲取包含當前執行的代碼的程式集 //var path1 = AppDomain.CurrentDomain.BaseDirectory + "\\bin"; //另一種寫法 string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); path = Path.GetDirectoryName(path); //創建一個程式集目錄,用於從一個程式集獲取所有的組件定義 var catalog = new DirectoryCatalog(path, "WIP_BLL.dll"); //創建容器 Container = new CompositionContainer(catalog); //_container.ComposeParts(this); //將部件(part)和宿主程式添加到組合容器,此時會初始化除了懶載入之外的Import的對象, //執行組合 【組合這一行代碼,並不影響我們的使用,有沒有皆可】 Container.ComposeParts(); } catch (Exception ex) {//吞掉異常 LogHelper.WriteErrorLogByLog4Net(typeof(IOCContainer), "註冊MEF出錯:ex:" + JsonConvert.SerializeObject(ex)); } } } /// <summary> /// 註冊 /// </summary> /// <returns></returns> public static IOCContainer RegisterContainer() { return instance; } }
Global.asax:
使用:
DataReportView ret = IOCContainer.Container.GetExport<IDayReportDataBLL>("DayReportData").Value.GetDayReportData(storeDateTime, storeDate);