using Raven.Client.Documents.Session; using System; using zero.Core.Database; namespace zero.Core.Collections { public abstract class CollectionSession : ICollectionSession { private IAsyncDocumentSession _session; private string _database; public CollectionSession(IZeroContext context) { Context = context; Store = context.Store; Database = Store.ResolvedDatabase; } /// /// Zero context /// protected readonly IZeroContext Context; /// /// Document store /// protected readonly IZeroStore Store; /// /// Create an an async document session /// protected IAsyncDocumentSession Session { get { if (_session != null) { return _session; } _session = Store.OpenAsyncSession(Database ?? Store.ResolvedDatabase); _session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); return _session; } } /// public string Database { get => _database; set { if (value != _database) { _session?.Dispose(); _session = null; _database = value; } } } /// public Guid Guid { get; private set; } = Guid.NewGuid(); /// public virtual void ApplyScope(string scope) { Database = scope is "shared" or "core" ? Context.Options.Raven.Database : Store.ResolvedDatabase; } /// public void Dispose() { Session?.Dispose(); } } public interface ICollectionSession : IDisposable { /// /// Guid for this instance /// Guid Guid { get; } /// /// The database to operate on. /// Is null by default, which uses the database from the resolved application. /// string Database { get; set; } /// /// Applies the scope to the service instance /// void ApplyScope(string scope); } }