如何配置Simple Injector IoC以使用RavenDB

Fre*_*ter 5 .net inversion-of-control ravendb asp.net-mvc-3 simple-injector

我在MVC 3 Web应用程序中使用Simple Injector作为IOC.我正在使用RavenDB进行数据存储.在mvc 3应用程序中使用RavenDB有几个注意事项.我搜索了一些关于如何连接IoC以使用RavenDB,但还没有找到如何连接简单的注入器来使用RavenDB.任何人都可以解释如何连接简单的注入器在MVC 3 Web应用程序中使用RavenDB?

谢谢.

Fre*_*ter 14

根据RavenDb教程,您的应用程序只需要一个IDocumentStore实例(我假设每个数据库).A IDocumentStore是线程安全的.它生成IDocumentSession实例,它们代表RavenDB中的一个工作单元,并且它们不是线程安全的.因此,你应该没有线程之间共享会话.

如何设置容器以便与RavenDb一起使用主要取决于应用程序设计.问题是:你想向消费者注入什么?那个IDocumentStore,还是IDocumentSession

当您使用时IDocumentStore,您的注册可能如下所示:

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

store.Initialize();

container.RegisterSingle<IDocumentStore>(store);
Run Code Online (Sandbox Code Playgroud)

消费者可能看起来像这样:

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();
        }            
    }
}
Run Code Online (Sandbox Code Playgroud)

因为IDocumentStore注入了消费者,消费者自己负责管理会话:创建,保存和处置.这对于小型应用程序非常方便,或者例如将RavenDb数据库隐藏在存储库后面,您可以session.SaveChanges()在该repository.Save(entity)方法中调用.

但是,我发现这种类型的工作单元对于更大的应用程序来说是有问题的.所以你能做的就是注入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());
Run Code Online (Sandbox Code Playgroud)

请注意,您需要Simple Injector ASP.NET Integration NuGet包(或包含SimpleInjector.Integration.Web.dll到您的项目,它包含在默认下载中)才能使用RegisterPerWebRequest扩展方法.

现在的问题是,在哪里打电话session.SaveChanges()

关于为每个网络请求注册作品单元存在一个问题,该问题也解决了有关的问题SaveChanges.请仔细看看这个答案:每个网络请求一个DbContext ...为什么?.当您更换的话DbContextIDocumentSessionDbContextFactoryIDocumentStore,你将能够在RavenDb的情况下阅读.请注意,在使用RavenDb时,商业交易或交易的概念可能并不重要,但老实说我不知道​​.这是你必须自己找到的东西.