簡體   English   中英

如何為SharpRepository的InMemoryRepository提供種子?

[英]How can I seed SharpRepository's InMemoryRepository?

正如標題所說,我如何使用一些虛擬數據為SharpRepository's InMemoryRepository提供種子?

我在配置中嘗試了這個:

var sharpRepositoryConfiguration = new SharpRepositoryConfiguration();
sharpRepositoryConfiguration.AddRepository(new InMemoryRepositoryConfiguration("inmemory"));
sharpRepositoryConfiguration.DefaultRepository = "inmemory";
var repo = sharpRepositoryConfiguration.GetInstance<Account>().Add(new [] { .... });

return new StructureMapDependencyResolver(sharpRepositoryConfiguration);

但是,當在我的控制器中解析存儲庫時,數據不存在。 我理解InMemoryRepository可以作為內存中的數據存儲 - 但是InMemoryRepository純粹只是將數據存儲在存儲庫中並且永遠不會將它們推送到底層的內存數據存儲中嗎?

能夠進行單元測試和模擬SharpRepository非常好,但是如果沒有能夠看到一些種子數據進入我的視圖,我就無法真正開發:(

編輯:我設法通過將我的存儲庫實現設置為單例:

x.For<IAccountRepository>()
    .Singleton()
    .Use<SharpRepositoryAccountRepository>();

然后將其注入我的控制器。 通過將其設置為單例,數據會在請求之間保持不變。

InMemoryRepositoryConfiguration每次都返回一個新的存儲庫(請參閱此處的工廠源代碼),因此如果將其設置為transient(而不是singleton),則不適合依賴注入。

如果你試圖在單元測試中使用它並試圖保持在內存中,看看CacheRepository ,我相信這將是你想開箱即用的方式:

var sharpRepositoryConfiguration = new SharpRepositoryConfiguration();
sharpRepositoryConfiguration.AddRepository(new CacheRepositoryConfiguration("inmemory"));
sharpRepositoryConfiguration.DefaultRepository = "inmemory";
var repo = sharpRepositoryConfiguration.GetInstance<Account>().Add(new [] { .... });

return new StructureMapDependencyResolver(sharpRepositoryConfiguration);

它默認使用InMemoryCachingProvider ,它使用MemoryCache進行持久化。 如果您有更多的存儲庫以避免它們相互踩踏,請向CacheRepositoryConfiguration構造函數添加前綴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM