5

我正在使用Simple Injector作爲MVC 3 Web應用程序中的IOC。我正在使用RavenDB進行數據存儲。在mvc 3應用程序中使用RavenDB有幾個注意事項。我已經搜索了一些如何連接IoC以使用RavenDB,但還沒有找到如何連接簡單的注入器以使用RavenDB。任何人都可以解釋如何連接簡單的注入器以在MVC 3 Web應用程序中使用RavenDB?如何配置Simple Injector IoC以使用RavenDB

謝謝。

回答

13

根據RavenDb tutorial,您的應用程序只需要一個IDocumentStore實例(根據我假設的每個數據庫)。 A IDocumentStore是線程安全的。它生成IDocumentSession實例,它們代表RavenDB中的unit of work,這些實例是而不是線程安全的。您應該因此而不是共享線程之間的會話。

如何設置用於RavenDb的容器主要取決於應用程序設計。問題是:你想向消費者注入什麼? IDocumentStoreIDocumentSession

當你用IDocumentStore去,你的註冊看起來是這樣的:

// Composition Root 
IDocumentStore store = new DocumentStore 
{ 
    ConnectionStringName = "http://localhost:8080" 
}; 

store.Initialize(); 

container.RegisterSingle<IDocumentStore>(store); 

消費者可能是這樣的:

public class ProcessLocationCommandHandler 
    : ICommandHandler<ProcessLocationCommand> 
{ 
    private readonly IDocumentStore store; 

    public ProcessLocationCommandHandler(IDocumentStore store) 
    { 
     this.store = store; 
    } 

    public void Handle(ProcessLocationCommand command) 
    { 
     using (var session = this.store.OpenSession()) 
     { 
      session.Store(command.Location); 

      session.SaveChanges(); 
     }    
    } 
} 

因爲IDocumentStore注入,消費者自己負責管理會話:創建,保存和處理。這對於小型應用程序非常方便,或者例如將RavenDb數據庫隱藏在repository後面,其中您在repository.Save(entity)方法內調用session.SaveChanges()

但是,我發現這種類型的工作單元的使用對於較大的應用程序來說是有問題的。所以你可以做的是,將IDocumentSession注入消費者。在這種情況下,您的註冊看起來是這樣的:

IDocumentStore store = new DocumentStore 
{ 
    ConnectionStringName = "http://localhost:8080" 
}; 

store.Initialize(); 

// Register the IDocumentSession per web request 
// (will automatically be disposed when the request ends). 
container.RegisterPerWebRequest<IDocumentSession>(
    () => store.OpenSession()); 

請注意,您所需要的Simple Injector ASP.NET Integration NuGet package(或包括SimpleInjector.Integration.Web.dll到您的項目,其中包括在默認下載)是能夠使用RegisterPerWebRequest擴展方法。

現在的問題變成了,在哪裏撥打session.SaveChanges()

關於註冊每個Web請求的作品單元有一個問題,它也解決了關於SaveChanges的問題。請仔細看看這個答案:One DbContext per web request…why?。當您用IDocumentSessionDbContextFactory替換單詞DbContextIDocumentStore時,您將能夠在RavenDb的上下文中閱讀它。請注意,也許商業交易或交易的概念在使用RavenDb時並不那麼重要,但我真的不知道。這是你必須自己找出來的。

相關問題