MEF在WCF REST中實際應用2(Global.asax註冊)

IOCContainer文件:ui

 

 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:this

 

使用:spa

   DataReportView ret = IOCContainer.Container.GetExport<IDayReportDataBLL>("DayReportData").Value.GetDayReportData(storeDateTime, storeDate);
相關文章
相關標籤/搜索