【发布时间】:2016-02-17 12:03:27
【问题描述】:
我一直按照“Microsoft Enterprise Library 5.0”文档中的步骤创建一个 HTTP 模块,以将 Enterprise Library 容器的引用注入到 ASP.NET Web 应用程序的页面中。
它包含以下代码(也出现在网上here):
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;
}
}
}
}
}
此代码及其附带的说明存在许多问题。
1) 说明中没有提到该代码的放置位置。由于它是一个类,所以我将它放在我的 ASP.NET 网站项目的 App_Code 文件夹中。
其实,下面是这段代码的说明:
创建一个新的 ASP.NET HTTP 模块类(例如,命名为 UnityHttpModule ) 在您的项目中捕获 PreRequestHandlerExecute 事件并执行遍历 当前页面请求的完整控制树,应用Unity 每个控件的 BuildUp 方法。
2) HttpContext.Current.Application.GetContainer() 方法对我来说不存在,即使我使用了相同的 DLL 引用(我正在编码在 .NET 4.0 中)。
3) OnPageInitComplete 事件引用了一个“上下文”变量...在此上下文中似乎不存在。
关于我在这里缺少什么的任何想法?
【问题讨论】:
标签: c# asp.net .net enterprise-library