RavenDB-构建会话工厂,Singleton DocumentStore工厂、RavenDB、DocumentStore、Singleton

2023-09-03 14:18:33 作者:执手不离

我是RavenDb的新手。我构建了RavenDB会话工厂,如下面的代码所示。这个想法在很大程度上是由我们构建NHibernateSessionHelpers的方式驱动的。我希望这在生产中能起到很好的作用。RavenDB专家对此有什么改进建议吗?

public class MXRavenDbSessionHelper
{        
    //---All new lazy singleton that's thread safe.---        
    private static Lazy<IDocumentStore> _lazyDocStore = new Lazy<IDocumentStore>(() => InitializeSessionFactory());

    private MXRavenDbSessionHelper() { }

    private static IDocumentStore SessionFactory
    {
        get
        {
            return _lazyDocStore.Value;
        }
    }

    public static IDocumentSession OpenSession()
    {
        return SessionFactory.OpenSession();
    }

    private static IDocumentStore InitializeSessionFactory()
    {
        var _docStore = new DocumentStore { ConnectionStringName = "RavenDBConnString", DefaultDatabase = "MXMunky" }; //One more way is this : _store = new DocumentStore { Url = "http://localhost:7000" };
        _docStore.Initialize();            
        _docStore.Conventions.IdentityPartsSeparator = "-";
        IndexCreation.CreateIndexes(typeof(Location).Assembly, _docStore);

        return _docStore;
    }
}

推荐答案

我认为您不需要单独保存_docStore。参见Jon Skeet's singleton patterns(#6)。

RavenDB数据库 RavenDB数据库官方版下载 数据库软件 绿软家园

除此之外,我看不出有什么特别的问题。

在进行单元测试时,我会小心不要使用它。在那里,您实际上确实希望为每个测试创建一个新的docstore实例,并且它们应该得到正确的处理。