0

我想將我的控制器轉換爲使用DI。我必須做些什麼才能使我的界面至少與其引用的方法一樣可訪問?

基礎上article here,我現在已經有了這個代碼:

namespace HandheldServer.Controllers 
{ 
    public class DuckbillsController : ApiController 
    { 
     static IDuckbillRepository _platypiRepository; 

     public DuckbillsController(IDuckbillRepository platypiRepository) 
     { 
      if (platypiRepository == null) 
      { 
       throw new ArgumentNullException("platypiRepository is null"); 
      } 
      _platypiRepository = platypiRepository; 
     } 

     public int GetCountOfDuckbillRecords() 
     { 
      return _platypiRepository.Get(); 
     } 

     public IEnumerable<Duckbill> GetBatchOfDuckbillsByStartingID(int ID, int CountToFetch) 
     { 
      return _platypiRepository.Get(ID, CountToFetch); 
     } 

     public void PostDuckbill(int accountid, string name) 
     { 
      _platypiRepository.PostDuckbill(accountid, name); 
     } 

     public HttpResponseMessage Post(Duckbill Duckbill) 
     { 
      Duckbill = _platypiRepository.Add(Duckbill); 
      var response = Request.CreateResponse<Duckbill>(HttpStatusCode.Created, Duckbill); 
      string uri = Url.Route(null, new { id = Duckbill.Id }); 
      response.Headers.Location = new Uri(Request.RequestUri, uri); 
      return response; 
     } 
    } 
} 

...但它不編譯;我得到的,「可訪問性不一致:參數類型‘HandheldServer.Models.IDuckbillRepository’大於法‘HandheldServer.Controllers.DuckbillsController.DuckbillsController(HandheldServer.Models.IDuckbillRepository)’不易進入」

接口參數類型中提到錯誤信息是:

using System.Collections.Generic; 

namespace HandheldServer.Models 
{ 
    interface IDuckbillRepository 
    { 
     int Get(); 
     IEnumerable<Duckbill> Get(int ID, int CountToFetch); 
     Duckbill Add(Duckbill item); 
     void Post(Duckbill dept); 
     void PostDuckbill(int accountid, string name); 
     void Put(Duckbill dept); 
     void Delete(int Id); 
    } 
} 

我需要做些什麼來解決這個錯誤味精?

回答

4

你需要明確標示interfacepublic

public interface IDuckbillRepository 
{ 
    // .... 
} 

另外,不要將其標記static在你的控制器。

+0

它在文章中是靜態的。 –

+2

它不應該。假設存儲庫設置正確..它應該重新創建每個請求..就像你的控制器。一個靜態屬性將生活在appdomain的生命週期中。如果存儲庫是在「每個請求」生命週期中設置的(因爲它應該是)..那麼你可能會得到隨機錯誤,更多的請求扔在控制器。 –

相關問題