1. 程式人生 > >在asp.net頁面上得到Castle容器的實例

在asp.net頁面上得到Castle容器的實例

exceptio prot object man net cast initial oid clas

在項目中使用Castle IOC容器,Asp.net程序中如何得到Castle容器內。

可以如下實現:

1、Gloabal實現接口IContainerAccessor

public class Global : System.Web.HttpApplication, IContainerAccessor
{

/// <summary>
/// 必需的設計器變量。
/// </summary>
private System.ComponentModel.IContainer components = null;
private static WindsorContainer container;

public Global()
{
InitializeComponent();
}

protected void Application_Start(Object sender, EventArgs e)
{
container = new MyContainer(new XmlInterpreter("app_config.xml"));
}

protected void Session_Start(Object sender, EventArgs e)
{

}

……
protected void Application_End(Object sender, EventArgs e)
{
container.Dispose();
}

#region IContainerAccessor implementation

public IWindsorContainer Container
{
get { return container; }
}

}

2、使用如下類來獲取容器實例,這段代碼來自Castle.MVC
/// <summary>
/// Uses the HttpContext and the <see cref="IContainerAccessor"/>
/// to access the container instance.
/// </summary>
public abstract

class ContainerWebAccessorUtil
{

/// <summary>
/// 從application中獲取一個容器實例
/// </summary>
/// <returns>返回一個 IWindsorContainer</returns>
public static IWindsorContainer ObtainContainer()
{

IContainerAccessor containerAccessor =

HttpContext.Current.ApplicationInstance as IContainerAccessor;
if (containerAccessor == null)
{
throw new ApplicationException("你必須在HttpApplication中實現接口 IContainerAccessor 暴露容器的屬性);

}

IWindsorContainer container = containerAccessor.Container;
if (container == null)
{
throw new ApplicationException("HttpApplication 得不到容器的實例");
}
return container;

}
}

3、在具體的用戶控件,頁面的後置代碼中通過ContainerWebAccessorUtil. ObtainContainer()獲取容器實例。當然如果使用Castle.MVC,MVC框架也是這樣用的,自己就不要這麽麻煩了,可以將這個寫在頁面和控件的基類中。

在asp.net頁面上得到Castle容器的實例