-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
87 lines (75 loc) · 3.09 KB
/
Program.cs
File metadata and controls
87 lines (75 loc) · 3.09 KB
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
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Starcounter.Database;
using Starcounter.Database.ChangeTracking;
using Starcounter.Database.Extensions;
namespace Hooks
{
[Database]
public abstract class Person : IDeleteAware
{
public abstract string Name { get; set; }
public void OnDelete(IDatabaseContext db) => Console.WriteLine($"{Name} is about to be deleted.");
}
public class RelevantChanges
{
public List<(ChangeType ChangeType, Type ObjectType, ulong Oid)> Changes { get; protected set; } = new List<(ChangeType ChangeType, Type ObjectType, ulong Oid)>();
}
class Program
{
static void Main(string[] args)
{
using var services = new ServiceCollection()
.AddStarcounter($"Database=./.database/Hooks")
.Decorate<ITransactor, OnDeleteTransactor>()
.Decorate<ITransactor, OnCommitTransactor<RelevantChanges>>()
.Configure<OnCommitTransactorOptions<RelevantChanges>>(o =>
{
o.OnBeforeCommit = db =>
{
var context = new RelevantChanges();
foreach (var change in db.ChangeTracker.Changes)
{
context.Changes.Add((change.Type, db.GetUserDefinedType(change.Oid), change.Oid));
Console.WriteLine($"{change.Type} of an object with id {change.Oid} is about to be committed.");
}
return context;
};
o.OnAfterCommit = context =>
{
foreach (var change in context.Changes)
{
Console.WriteLine($"{change.ChangeType} of an object with id {change.Oid} has just been committed.");
}
};
})
.BuildServiceProvider();
var transactor = services.GetRequiredService<ITransactor>();
var id = transactor.Transact(db =>
{
var per = db.Insert<Person>();
per.Name = "Per";
return db.GetOid(per);
});
transactor.Transact(db =>
{
var per = db.Get<Person>(id);
per.Name = "Per Samuelsson";
});
transactor.Transact(db =>
{
var per = db.Get<Person>(id);
db.Delete(per);
});
// Output:
// Insert of an object with id 1 is about to be committed.
// Insert of an object with id 1 has just been committed.
// Update of an object with id 1 is about to be committed.
// Update of an object with id 1 has just been committed.
// Per Samuelsson is about to be deleted.
// Delete of an object with id 1 is about to be committed.
// Delete of an object with id 1 has just been committed.
}
}
}