可以如下实现:
1、Gloabal实现接口IContainerAccessor
public class Global : System.Web.HttpApplication, IContainerAccessor
{<o:p></o:p>
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
private static WindsorContainer container;
public Global()
{
InitializeComponent();
} <o:p></o:p>
protected void Application_Start(Object sender, EventArgs e)
{
container = new MyContainer(new XmlInterpreter("app_config.xml"));
} <o:p></o:p>
protected void Session_Start(Object sender, EventArgs e)
{<o:p></o:p>
}
……
protected void Application_End(Object sender, EventArgs e)
{
container.Dispose();
} <o:p></o:p>
#region IContainerAccessor implementation
public IWindsorContainer Container
{
get { return container; }
}
}<o:p></o:p>
2、使用如下类来获取容器实例,这段代码来自Castle.MVC
/// <summary>
/// Uses the HttpContext and the <see cref="IContainerAccessor"/>
/// to access the container instance.
/// </summary>
public abstract class ContainerWebAccessorUtil
{<o:p></o:p>
/// <summary>
/// 从application中获取一个容器实例
/// </summary>
/// <returns>返回一个 IWindsorContainer</returns>
public static IWindsorContainer ObtainContainer()
{<o:p></o:p>
IContainerAccessor containerAccessor = <o:p></o:p>
HttpContext.Current.ApplicationInstance as IContainerAccessor;
if (containerAccessor == null)
{
throw new ApplicationException("你必须在HttpApplication中实现接口 IContainerAccessor 暴露容器的属性”);<o:p></o:p>
} <o:p></o:p>
IWindsorContainer container = containerAccessor.Container;
if (container == null)
{
throw new ApplicationException("HttpApplication 得不到容器的实例");
}
return container;<o:p></o:p>
}
} <o:p></o:p>
3、在具体的用户控件,页面的后置代码中通过ContainerWebAccessorUtil. ObtainContainer()获取容器实例。当然如果使用Castle.MVC,MVC框架也是这样用的,自己就不要这么麻烦了,可以将这个写在页面和控件的基类中。
原文:http://shanyou.cnblogs.com/archive/2005/10/28/264103.html