-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnitOfWork.cs
93 lines (78 loc) · 2.51 KB
/
UnitOfWork.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using Marten;
using Marten.Events;
using MartenHelp.Projections;
using System.Reflection;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MartenHelp
{
public class UnitOfWork : IUnitOfWork, IDisposable
{
private IDocumentStore _store;
private IDocumentSession session;
#region Constructors
public UnitOfWork(string connectionString, EnvironmentType env)
{
_store = StoreFactory.CreateDocumentStore(connectionString, env);
if (!StartSession()) {
throw new Exception("Could not start session.");
}
}
public UnitOfWork(IDocumentStore DocumentStore)
{
_store = DocumentStore;
if (!StartSession()) {
throw new Exception("Could not start session.");
}
}
#endregion
private Boolean StartSession()
{
this.session = _store.LightweightSession();
return this.session.Connection != null;
}
public void Dispose()
{
EndSession();
}
private Boolean EndSession()
{
if (this.session != null)
{
this.session.Dispose();
}
return true;
}
public async Task<T> AppendEvent<T>(Guid StreamId, MartenHelp.Events.Event newEvent) where T : class, new()
{
this.session.Events.Append(StreamId, newEvent);
var stream = await this.session.Events.AggregateStreamAsync<T>(StreamId);
return stream;
}
public async Task<T> GetStreamState<T>(Guid StreamId) where T : class, new()
{
return await this.session.Events.AggregateStreamAsync<T>(StreamId);
}
public async Task SaveChanges()
{
await this.session.SaveChangesAsync();
}
public IQueryable<T> CreateQueryable<T>() where T : class, new()
{
return session.Query<T>();
}
public async Task<Guid> CreateNewStream<T>() where T: class, new()
{
var id = this.session.Events.StartStream<T>().Id;
return id;
}
public async Task<Guid> CreateNewStream<T>(params Events.Event[] events) where T: class, new()
{
var id = this.session.Events.StartStream<T>(events).Id;
return id;
}
}
public enum EnvironmentType {dev, qa, prod}
}