在asp.net頁面上得到Castle容器的執行個體

來源:互聯網
上載者:User
 在項目中使用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架構也是這樣用的,自己就不要這麼麻煩了,可以將這個寫在頁面和控制項的基類中。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.