似乎文档组织得很糟糕。
针对(2),没有解释的是,HttpContext.Current.Application.GetContainer()方法实际上是一个扩展方法,其实现方式如所示代码here http://msdn.microsoft.com/en-us/library/ff664704%28v=pandp.50%29.aspx.
要使用此扩展方法,您只需导入“Unity.Web”命名空间。
这是扩展方法的副本:
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();
}
}
}
}
关于依赖注入模块代码,我实际上只是使用了基本方法 http://msdn.microsoft.com/en-us/library/ff664622%28v=pandp.50%29.aspx用于获取容器的实例,就我而言,它也同样有效。文档说依赖注入 HTTP 模块代码提高了“可测试性”和“可发现性”,这有点模糊。
无论如何,这是基本方法的代码:
protected void Application_Start(object sender, EventArgs e)
{
Application.Lock();
try
{
var myContainer = Application["EntLibContainer"] as IUnityContainer;
if (myContainer == null)
{
myContainer = new UnityContainer();
myContainer.AddExtension(new EnterpriseLibraryCoreExtension());
// Add your own custom registrations and mappings here as required
Application["EntLibContainer"] = myContainer;
}
}
finally
{
Application.UnLock();
}
}
因此,扩展代码就位,并且在我的 global.asax 文件中创建用于创建 Enterprise Library 容器实例的代码后,唯一要做的就是编写代码以根据需要获取容器实例。因此,当我想获取 LogWriter 类的实例时,我会这样写:
using Unity.Web;
public LogWriter getLogWriter()
{
var container = HttpContext.Current.Application.GetContainer();
return container.Resolve<LogWriter>();
}
需要 Unity.Web 命名空间来允许我们调用 GetContainer() 扩展方法。