.net – 如何配置Simple Injector IoC以使用RavenDB

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

谢谢.

解决方法

根据 RavenDb tutorial,您的应用程序只需要oneIDocumentStore实例(我假设每个数据库). IDocumentStore是线程安全的.它生成IDocumentSession实例,它们代表RavendB中的 unit of work,并且它们不是线程安全的.因此,您不应在线程之间共享会话.

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

当您使用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?.当您使用IDocumentStore替换带有IDocumentSession和DbContextFactory的单词DbContext时,您将能够在Ravendb的上下文中读取它.请注意,在使用Ravendb时,商业交易或交易的概念可能并不重要,但老实说我不知道​​.这是你必须自己找到的东西.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....