2013-11-26 141 views
1

存儲庫模式很容易實現,但我面臨一個小問題。如果有人覺得我的代碼很長,我很抱歉,但是當我明白時,這對我來說很有價值。瞭解存儲庫模式

我創建了一個簡單的界面,像以下內容: -

public interface IBookRepository 
{ 
    List<Books> GetUsers(); 
    void Save(); 
} 

以下是其實現IBookRepository接口

public class BookRepository : IBookRepository 
{ 
    private PosContext context; 

    public BookRepository(PosContext context) 
    { 
     this.context = context; 
    } 

    public List<Books> GetUsers() 
    { 
     return context.Book.ToList(); 
    } 
} 

以下是BookController的類: -

public class BookController : Controller 
{ 
    #region Private member variables... 
    private IBookRepository bookRepository; 
    #endregion 

    public BookController() 
    { 
     bookRepository = new BookRepository(new PosContext()); 
    } 

    public ActionResult Index() 
    { 
     var query = (from c in bookRepository.GetUsers() 
        select c).ToList(); 

     //var userList = from user in userRepository.GetUsers() select user; 
     var users = new List<Books>().ToList(); 

     ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

     return View(users); 
    } 
} 

謝謝閱讀上面的代碼: - 現在我的問題是在下面的代碼行

private IBookRepository bookRepository; 
public BookController() 
{ 
    bookRepository = new BookRepository(new PosContext()); 
} 

在在第一行上面的代碼我們寫bookRepository基本上IBookRepository接口的引用(如我讀的地方)。我們爲什麼在這裏使用它?如果我直接寫下面這行代碼,它也可以很好地工作。

private BookRepository bookRepository; 
public BookController() 
{ 
    bookRepository = new BookRepository(new PosContext()); 
} 

請上次的代碼快照注意我用IBookRepository並在最後的代碼shapshort我只使用BookRepository我不明白,這兩個代碼的差使其中有沒有錯誤,如果有人請澄清我的理解我應非常感謝和感激。

謝謝。

回答

0

你注意到的是正確的。當你像這樣構造它時沒有多大用處。您可以改進它象下面這樣:

private IBookRepository _bookRepository; 
public BookController(IBookRepository bookRepository) 
{ 
    _bookRepository = bookRepository; 
} 

在這裏,自然的問題是「誰在傳遞bookRepository到構造函數?」。在.NET中,我們可以使用像Ninject,Unity等依賴注入框架來完成它。

依賴注入框架基本上使您能夠將接口映射到具體類,以便當運行時查找IBookRepository時,將返回new BookRepository()的實例。

有什麼好處,你可能會問。答案是單元測試。然後你可以做如下的單元測試。通過使我們的控制器依賴於IBookRepository而不是BookRepository,我們可以實現單元測試。注意現在我們可以通過任何IBookRepository,比如FakeBookRepository進行單元測試。

[Test] 
public void Index_Passes_Correct_Model_To_View() 
{ 
    //Arrange 
    IBookRepository bookRepository = new FakeBookRepository(); 
    var controller = new BookController(bookRepository); 

    //Act 
    var result = (ViewResult) controller.Index(); 

    // Assert 
    var listBooks = result.ViewData.Model; 
    Assert.Equal(1, listBooks.Count()); 
} 

其中

public class FakeBookRepository : IBookRepository 
{ 
    public List<Books> GetUsers() 
    { 
     return new List<Book> { new Book() { Id=1 , Name = "abc" } }; 
    } 
}