-
Notifications
You must be signed in to change notification settings - Fork 0
/
StoreFactory.cs
75 lines (68 loc) · 2.91 KB
/
StoreFactory.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Marten;
using Marten.Events.Projections;
namespace MartenHelp
{
internal class StoreFactory
{
private static object syncRoot = new Object();
private static volatile Dictionary<string, IDocumentStore> stores = new Dictionary<string, IDocumentStore>();
private static Type[] EventTypes = new Type[0];
private static Type[] ProjectionTypes = new Type[0];
public static IDocumentStore CreateDocumentStore(string connectionString, EnvironmentType env)
{
if (!stores.Keys.Contains(connectionString))
{
lock (syncRoot)
{
if (!stores.Keys.Contains(connectionString))
{
stores.Add(connectionString, GenerateDocumentStore(connectionString, env));
}
}
}
return stores[connectionString];
}
private static IDocumentStore GenerateDocumentStore(string connectionString, EnvironmentType env)
{
if (ProjectionTypes == null | ProjectionTypes.Length == 0)
{
ProjectionTypes = GetEventTypes(typeof(UnitOfWork).GetTypeInfo().Assembly, "MartenHelp.Projections");
}
if (EventTypes == null || EventTypes.Length == 0)
{
EventTypes = GetEventTypes(typeof(UnitOfWork).GetTypeInfo().Assembly, "MartenHelp.Events");
}
var autoCreate = (env == EnvironmentType.dev) ? AutoCreate.All : AutoCreate.CreateOrUpdate;
IDocumentStore _store = DocumentStore.For(_ =>
{
_.AutoCreateSchemaObjects = autoCreate;
_.Connection(connectionString);
});
EventTypes.ToList().ForEach(Event =>
{
if (!Event.GetTypeInfo().IsAbstract && Event.GetTypeInfo().IsClass)
_store.Events.AddEventType(Event);
});
var inline = typeof(Marten.Events.Projections.ProjectionCollection);
MethodInfo method = inline.GetMethod("AggregateStreamsWith");
ProjectionTypes.ToList().ForEach(Projection =>
{
// Only Register if it is not abstract, is a class, and implements IProjection
if (!Projection.GetTypeInfo().IsAbstract && Projection.GetTypeInfo().IsClass)
{
MethodInfo genericMethod = method.MakeGenericMethod(Projection);
genericMethod.Invoke(_store.Events.InlineProjections, null);
}
});
return _store;
}
private static Type[] GetEventTypes(Assembly assembly, string nameSpace)
{
return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
}
}
}