參考:http://shanyou.cnblogs.com/archive/2005/10/28/264103.html
在項目中使用Castle IOC容器,可以在Asp.Net頁面上這樣得到Castle容器:
1. 在Global.asax.cs中實現IContainerAccessor
Global.asax
public class Global : System.Web.HttpApplication, IContainerAccessor
{
private static WindsorContainer container;
protected void Application_Start(object sender, EventArgs e)
{
//CacheManager.LoadCacheFile(); 緩衝管理類
container = new WindsorContainer(new XmlInterpreter(new ConfigResource()));
}
protected void Application_End(object sender, EventArgs e)
{
}
public IWindsorContainer Container
{
get { return container; }
}
}
2. 擷取容器執行個體
ContainerAccessorUtil
public class ContainerAccessorUtil
{
private ContainerAccessorUtil()
{
}
/// <summary>
/// 獲得容器裡的所有執行個體
/// </summary>
/// <returns>所有執行個體的List</returns>
public static IWindsorContainer GetContainer()
{
IContainerAccessor containerAccessor = HttpContext.Current.ApplicationInstance as IContainerAccessor;
if (containerAccessor == null)
{
throw new Exception("You must extend the HttpApplication in your web project " +
"and implement the IContainerAccessor to properly expose your container instance" + "/n" +
"你必須在HttpApplication中實現介面 IContainerAccessor 暴露容器的屬性");
}
IWindsorContainer container = containerAccessor.Container as IWindsorContainer;
if (container == null)
{
throw new Exception("The container seems to be unavailable in " +
"your HttpApplication subclass" + "/n" + "HttpApplication 得不到容器的執行個體");
}
return container;
}
}
3. 在具體頁面的相關基類內,通過ContainerAccessorUtil.GetContainer()擷取容器執行個體
如:
GetContainer
public ISqlMapper sqlMap = (ContainerAccessorUtil.GetContainer())["SqlServerSqlMap"] as ISqlMapper;
public static IContractBiz iContractBiz = ContainerAccessorUtil.GetContainer()["CCLOG.ContractBiz"] as IContractBiz;
IBasicInfoBiz iBasicInfoBiz = ContainerAccessorUtil.GetContainer()["CCLOG.BasicInfoBiz"] as IBasicInfoBiz;
//...
要將IBatisNet交給Castle來管理,所以ISqlMapper的執行個體也必須從Castle容器中擷取,這樣Castle才能真正的管理IBatisNet。
從容器中獲得ISqlMapper執行個體的方法:BaseSqlMapDao.cs
public ISqlMapper sqlMap = (ContainerAccessorUtil.GetContainer())["SqlServerSqlMap"] as ISqlMapper;
其中"sqlServerSqlMap"即是在我們配置IBatisNet Facility時指定的。
<facility id="ibatis" type="Castle.Facilities.IBatisNetIntegration.IBatisNetFacility, Castle.Facilities.IBatisNetIntegration" >
<sqlMap id="SqlServerSqlMap" config="SqlMap.config" />
</facility>
附:
關於Global.asax檔案:
Global.asax 檔案,有時候叫做 ASP.NET 應用程式檔案,提供了一種在一個中心位置響應應用程式級或模組層級事件的方法。你可以使用這個檔案實現應用程式安全性以及其它一些任務。
Global.asax 位於應用程式根目錄下。ASP.NET 頁面架構能夠自動識別出對Global.asax 檔案所做的任何更改。
Global.asax 包含很多事件,常被用於安全性方面,可以用來處理應用程式級任務,比如使用者身分識別驗證、應用程式啟動以及處理使用者會話等。