2009-09-25 32 views
2

我試圖在現有的Web窗體應用程序中引入依賴注入。該項目是作爲網站項目創建的(而不是Web應用程序項目)。我曾經見過你的global.asax.cs創建全球一流的樣品,它看起來是這樣的:如何在Web窗體Web站點項目中連接Castle Windsor

public class GlobalApplication : HttpApplication, IContainerAccessor 
{ 
    private static IWindsorContainer container; 

    public IWindsorContainer Container 
    { 
     get { return container; } 
    } 

    protected void Application_Start(object sender, EventArgs e) 
    { 
     if (container == null) 
     { 
      container = <...> 
     } 
    } 

但是,在一個網站項目,如果你問添加一個全局類,它增加了全球唯一其中的.asax包含服務器端腳本標籤:

<%@ Application Language="C#" %> 

<script runat="server"> 

void Application_Start(object sender, EventArgs e) 
{ 
    // Code that runs on application startup 

} 

似乎沒有成爲我從HttpApplication的(和IContainerAccessor)得出這裏的一種方式。還是我錯過了明顯的東西?

回答

5

我找到了一個方法。 Global.asax文件應該只包含:

<%@ Application Language="C#" Inherits="GlobalApp" %> 

然後在App_Code文件夾中,我創建GlobalApp.cs

using System; 
using System.Web; 
using Castle.Windsor; 

public class GlobalApp : HttpApplication, IContainerAccessor 
{ 
    private static IWindsorContainer _container; 
    private static IWindsorContainer Container { 
     get 
     { 
      if (_container == null) 
       throw new Exception("The container is the global application object is NULL?"); 
      return _container; 
     } 
    } 

    protected void Application_Start(object sender, EventArgs e) { 

     if (_container == null) { 
      _container = LitPortal.Ioc.ContainerBuilder.Build(); 
     } 
    } 

    IWindsorContainer IContainerAccessor.Container 
    { 
     get { 
      return Container; 
     } 
    } 
} 

使_container靜態看來很重要的。我發現GlobalApp類的對象多次創建。 Application_Start方法僅在第一次被調用。當我將_container作爲非靜態字段時,它對於該類的第二個和隨後的實例化爲空。

要引用容器容易在代碼的其他部分,我定義了一個輔助類Ioc.cs

using System.Web; 
using Castle.Windsor; 

public static class Ioc 
{ 
    public static IWindsorContainer Container { 
     get { 
      IContainerAccessor containerAccessor = HttpContext.Current.ApplicationInstance as IContainerAccessor; 
      return containerAccessor.Container; 
     } 
    } 
} 

這樣一來,代碼的其他部分,他們應該需要訪問容器可以用Ioc.Container.Resolve()

這聽起來像是正確的設置?

相關問題