2010-08-23 63 views
1

此問題與我的其他post有關。使用IoC容器作爲HttpHandler的服務定位器

好了,等一會兒有更多的混亂後,我決定這樣做。這似乎工作正常,當我運行它,雖然我在NUnit中收到以下錯誤:無法加載文件或程序集'Castle.Core,Version = 1.0.3.0,Culture = neutral,PublicKeyToken = 407dd0808d44fbdc'或其中一個依賴。定位的程序集清單定義與程序集引用不匹配。 (從HRESULT異常:0x80131040)所以不知道那裏發生了什麼?

只是想知道別人對設計的看法,以及是否有任何明顯的「不」或改進。即基礎處理程序的構造函數是實例化windsor組件的好地方,還是有更好的地方可以做到這一點?正如我在原始文章中所說的那樣,通過這種方式做事背後的想法是保持組件良好地分離並使單元測試變得容易。我還應該補充我是單元測試新手,嘲笑。謝謝!

public abstract class BaseHttpHandler : IHttpHandler 
{ 
    private HttpContext _httpContext; 
    private ILogger _logger; 
    private IDataRepository _dataRepository; 
    protected HttpRequest Request { get { return _httpContext.Request; } } 
    protected HttpResponse Response { get { return _httpContext.Response; } } 
    protected bool IsRequestFromUAD { get { return Request.UserAgent == null ? false : Request.UserAgent.Equals("UAD"); } } 
    protected ILogger Logger { get { return _logger; } } 
    protected IDataRepository DataRepository { get { return _dataRepository; } } 
    public virtual bool IsReusable { get { return false; } } 

    public BaseHttpHandler() 
    { 
     var container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle"))); 
     _logger = container.Resolve<ILogger>(); 
     _dataRepository = container.Resolve<IDataRepository>(); 
    } 

    public void ProcessRequest(HttpContext context) 
    { 
     _httpContext = context; 
     ProcessRequest(new HttpContextWrapper(context)); 
    } 

    public abstract void ProcessRequest(HttpContextBase context); 
} 

public class UADRecordHttpHandler : BaseHttpHandler 
{ 
    public override void ProcessRequest(HttpContextBase context) 
    { 
     if (IsRequestFromUAD) 
     { 
      using (var reader = new StreamReader(context.Request.InputStream)) 
      { 
       string data = reader.ReadToEnd(); 

       if (Logger != null) 
        Logger.Log(data); 

       if(DataRepository != null) 
        DataRepository.Write(data); 

       context.Response.Write(data); 
      } 
     } 
     else 
      ReturnResponse(HttpStatusCode.BadRequest); 
    } 
} 

回答

1

這是一個非常糟糕的事情要做,你在這裏做什麼。每個應用程序應該有一個容器實例,而使用此代碼時,每個請求都會有一個實例。

+0

嗨。感謝您的答覆。這是有道理的,(這是我認爲是這種情況,我認爲最好在其他地方創建容器,比如Application_Start(Global.asax.cs),但即使我創建了一個靜態服務定位器,就像Mauricio建議的那樣下面是如何做的HttpHandler的接入容器? – Matt 2010-08-23 23:46:44

1

關於NUnit中的錯誤:請確保您在GAC中沒有其他版本的Castle組件。如果是這樣,請卸載它們。

關於你的BaseHttpHandler:這個實現的問題是你正在創建一個新的容器。相反,每個應用程序使用一個容器,就像Krzysztof所說。使用靜態服務定位器,例如CommonServiceLocator。 (我從來不推薦這個,但它是少數幾個有意義的地方之一)。

+0

難道我不是簡單的容器添加到HttpApplicationState ?? 保護無效的Application_Start(對象發件人,EventArgs的){ Application.Add(「容器」,新WindsorContainer(新XmlInterpreter (新的ConfigResource(「城堡」)))); } – Matt 2010-08-24 00:32:30

+0

@Matt:是的,也可以工作 – 2010-08-24 00:46:07

+0

感謝您的輸入關於Castle.Core程序集的問題,我檢查了GAC,它並不在那裏? – Matt 2010-08-24 01:57:16