|
using System; |
|
using System.Collections.Generic; |
|
using System.Diagnostics; |
|
using System.Diagnostics.Contracts; |
|
using System.IO; |
|
using System.Threading; |
|
|
|
namespace biz.dfch.CS.EA.ProductModeler.Tests.Repository |
|
{ |
|
public class RepositorySingleton : IDisposable |
|
{ |
|
private static readonly object _syncRoot = new object(); |
|
private static readonly List<Action> _cleanupActions = new List<Action>(); |
|
|
|
private static int _instances; |
|
private static string _repoPathAndFileName; |
|
|
|
private static readonly Lazy<global::EA.Repository> _repository = new Lazy<global::EA.Repository>(() => |
|
{ |
|
var repository = new global::EA.Repository(); |
|
Contract.Assert(null != repository); |
|
_cleanupActions.Add(() => repository.Exit()); |
|
|
|
var isOpen = repository.OpenFile(_repoPathAndFileName); |
|
Contract.Assert(isOpen); |
|
|
|
return repository; |
|
}); |
|
|
|
// ReSharper disable once InconsistentlySynchronizedField |
|
public global::EA.Repository Repository => _repository.Value; |
|
|
|
public RepositorySingleton(string path) |
|
{ |
|
Contract.Requires(File.Exists(path)); |
|
|
|
Interlocked.Increment(ref _instances); |
|
|
|
if (_repository.IsValueCreated) return; |
|
|
|
lock (_syncRoot) |
|
{ |
|
if (_repository.IsValueCreated) return; |
|
|
|
_repoPathAndFileName = path; |
|
var result = _repository.Value; |
|
} |
|
} |
|
|
|
private static void ReleaseUnmanagedResources() |
|
{ |
|
if (0 != Interlocked.Decrement(ref _instances)) return; |
|
|
|
_cleanupActions.Reverse(); |
|
foreach (var action in _cleanupActions) |
|
{ |
|
try |
|
{ |
|
action.Invoke(); |
|
} |
|
catch (Exception ex) |
|
{ |
|
Debug.WriteLine(ex.Message); |
|
} |
|
} |
|
} |
|
|
|
public void Dispose() |
|
{ |
|
ReleaseUnmanagedResources(); |
|
GC.SuppressFinalize(this); |
|
} |
|
|
|
~RepositorySingleton() |
|
{ |
|
ReleaseUnmanagedResources(); |
|
} |
|
} |
|
} |
|
|
|
/** |
|
* Copyright 2018 d-fens GmbH |
|
* |
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
|
* you may not use this file except in compliance with the License. |
|
* You may obtain a copy of the License at |
|
* |
|
* http://www.apache.org/licenses/LICENSE-2.0 |
|
* |
|
* Unless required by applicable law or agreed to in writing, software |
|
* distributed under the License is distributed on an "AS IS" BASIS, |
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
* See the License for the specific language governing permissions and |
|
* limitations under the License. |
|
*/ |
|
|