標籤:style blog http color 使用 os strong io
本文出自:http://blog.csdn.net/sfbirp/article/details/5621272
您可以使用HTTP模組,一個到ASP.NET HttpApplicationState類的擴充,在Global.asax編寫代碼強制ASP.NET在每一個頁面請求時自動注入依賴的對象,就像在ASP.NET Web表單應用程式中討論的一樣.
下列方法顯示了一個合適的方法能夠擷取PreRequestHandlerExecute事件將它自己注入到ASP.NET的執行流水線,在每個頁面請求中通過容器的BuildUp方法運行Http模組,並擷取OnPageInitComplete事件。當OnPageInitComplete執行時模組代碼按照所有的控制項樹運行,並通過容器的BuildUp方法處理每個控制項。
BuildUp方法擷取已經存在的對象執行個體,處理並填充類的依賴,返回執行個體。如果沒有依賴則返回最初的執行個體。
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using Microsoft.Practices.Unity; namespace Unity.Web { public class UnityHttpModule : IHttpModule { public void Init(HttpApplication context) { context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; } public void Dispose() { } private void OnPreRequestHandlerExecute(object sender, EventArgs e) { IHttpHandler currentHandler = HttpContext.Current.Handler; HttpContext.Current.Application.GetContainer().BuildUp( currentHandler.GetType(), currentHandler); // User Controls are ready to be built up after page initialization is complete var currentPage = HttpContext.Current.Handler as Page; if (currentPage != null) { currentPage.InitComplete += OnPageInitComplete; } } // Build up each control in the page‘s control tree private void OnPageInitComplete(object sender, EventArgs e) { var currentPage = (Page)sender; IUnityContainer container = HttpContext.Current.Application.GetContainer(); foreach (Control c in GetControlTree(currentPage)) { container.BuildUp(c.GetType(), c); } context.PreRequestHandlerExecute -= OnPreRequestHandlerExecute; } // Get the controls in the page‘s control tree excluding the page itself private IEnumerable<Control> GetControlTree(Control root) { foreach (Control child in root.Controls) { yield return child; foreach (Control c in GetControlTree(child)) { yield return c; } } } } }
下面顯示了一個應用程式狀態的實現,並暴露一個靜態 GetContainer方法,這個方法能夠在
Application狀態中建立一個新的統一容器,如果不存在的話,或者返回一個存在的執行個體的引用。
using System.Web; using Microsoft.Practices.Unity; namespace Unity.Web { public static class HttpApplicationStateExtensions { private const string GlobalContainerKey = "EntLibContainer"; public static IUnityContainer GetContainer(this HttpApplicationState appState) { appState.Lock(); try { var myContainer = appState[GlobalContainerKey] as IUnityContainer; if (myContainer == null) { myContainer = new UnityContainer(); appState[GlobalContainerKey] = myContainer; } return myContainer; } finally { appState.UnLock(); } } } }