在asp.net页面上得到Castle容器的实例

本文介绍在ASP.NET应用程序中集成Castle IOC容器的方法。通过实现IContainerAccessor接口并在Global类中初始化容器,可以在整个应用中获取容器实例。具体步骤包括在启动时创建容器实例、在会话开始和结束时进行相应的操作,并提供了获取容器实例的实用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

可以如下实现:

1Gloabal实现接口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框架也是这样用的,自己就不要这么麻烦了,可以将这个写在页面和控件的基类中。

原文:http://shanyou.cnblogs.com/archive/2005/10/28/264103.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值