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

最新文章

  1. python 邮件
  2. Struts2拦截器模拟
  3. sql注入基于错误-单引号-字符型
  4. .net 使用PowerShell获取电脑中的UUID
  5. 使用 rqt_console 和 roslaunch---8
  6. oracle10 权限角色
  7. PLSQL Developer如何设置自动打开上次编辑的文件
  8. CSS禁止用户选择复制
  9. Bzoj1030:[JSOI2007]文本生成器
  10. AE的空间分析(转载)
  11. BZOJ_4530_[Bjoi2014]大融合_LCT
  12. 3-html 缩写-地址-文字方向-引用块-题注的格式
  13. npm 发布包和删除包(2019最新攻略)
  14. [uboot] (番外篇)uboot relocation介绍
  15. Linux查看日志定位问题
  16. 技术分享之AQS——内容提要
  17. 关于使用QTcpSocket的一些总结
  18. 洛谷P3557 GRA-Tower Defense Game [POI2013] 构造
  19. idea 连接数据库
  20. String对象的简单方法(特别讲解length()方法的实现。

热门文章

  1. RCC 2014 Warmup (Div. 2) A~C
  2. 从1KW条数据中筛选出1W条最大的数
  3. IE6—在链接click事件的响应函数中发送jsonp请求不生效
  4. unity, editable mesh
  5. unity5, UI Button &quot;On Button Down&quot;
  6. atitit.提升性能AppCache
  7. atitit. 管理哲学 大毁灭--- 如何防止企业的自我毁灭
  8. BootCamp支持软件6
  9. 如何让linux加载当前目录的动态库
  10. RabbitMQ系列一