微软企业库5.0学习笔记(10)ASP.NET模块依赖注入
本文出自: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(); } } } }