RavenDB的文档存储是你对数据库的主要访问点。它是 s 强烈建议 建议你在访问的每台服务器上只拥有一个文档存储的实例 存储器的单个实例。这通常意味着你 必须实现一个单子,以及所有的双重检查锁定 的胡说八道。上周,我在给RavenDB的一个课程 的课程,我偶然发现了一个非常好的编码模式。
public static class Global { private static readonly Lazy<IDocumentStore> theDocStore = new Lazy<IDocumentStore>(()=> { var docStore = new DocumentStore { ConnectionStringName = "RavenDB" }; docStore.Initialize(); //OPTIONAL: //IndexCreation.CreateIndexes(typeof(Global).Assembly, docStore); return docStore; }); public static IDocumentStore DocumentStore { get { return theDocStore.Value; } } }
这是一个非常可读的代码,它几乎处理了所有的 踩踏的东西,而不会掩盖你真正想做的事情。
当你有多个服务器时怎么办?那你怎么处理呢?同样的想法,再往前走一步。
public static class Global { private readonly static ConcurrentDictionary<string, Lazy<IDocumentStore>> stores = new ConcurrentDictionary<string, Lazy<IDocumentStore>>(); public static IDocumentStore GetDocumentStoreFor(string url) { return stores.GetOrAdd(url, CreateDocumentStore).Value; } private static Lazy<IDocumentStore> CreateDocumentStore(string url) { return new Lazy<IDocumentStore>(() => { var docStore = new DocumentStore { ConnectionStringName = url }; docStore.Initialize(); //OPTIONAL: //IndexCreation.CreateIndexes(typeof(Global).Assembly, docStore); return docStore; }); } }
这很好,很简单,是处理事情的正确方法。