2015-03-31 74 views
0

如果已在上一篇文章中回答了此問題,則表示歉意;我只是找不到針對我的問題的答案。正確的MVC存儲庫實例化

我正在看一個MVC教程視頻,並且在他們的一個控制器中,他們一直在以他們需要的每種方法實例化一個存儲庫。我已經習慣了這種從以前的ASP.NET DAL,但他們提出這樣的評論:

...我不應該在每一個方法實例庫,我 應該利用MVC的服務。 ..

我很想知道這意味着什麼,如果在我的控制器方法實例化存儲庫,我需要它將是不好的做法。

回答

1

我不是專家,但我認爲你應該在控制器的構造函數實例化你的倉庫只有一次這樣的:

public interface ISampleRepository { } 
public class SampleRepository : ISampleRepository { } 

public class HomeController : Controller 
{ 
    private ISampleRepository myRepository; 

    public HomeController() 
    { 
     myRepository = new SampleRepository(); 
    } 
} 

您不必例如你的資料庫中的每一個操作方法 。我不確定,但我想每次實例化存儲庫時都會創建一個新的數據庫上下文。

因此,多次實例化同一個存儲庫似乎對我來說太過分了。

相關問題