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时并不那么重要,但我真的不知道。这是你必须自己找出来的。

相关问题