forked from Particular/NServiceBus
/
FuncBuilder.cs
74 lines (61 loc) · 2.03 KB
/
FuncBuilder.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
namespace NServiceBus.Unicast.Tests.Helpers
{
using System;
using System.Collections.Generic;
using System.Linq;
using NServiceBus.ObjectBuilder;
public class FuncBuilder : IBuilder
{
IList<Tuple<Type, Func<object>>> funcs = new List<Tuple<Type, Func<object>>>();
public void Dispose()
{
}
public void Register<T>(Func<object> func)
{
Register(typeof(T),func);
}
public void Register(Type t,Func<object> func)
{
funcs.Add(new Tuple<Type, Func<object>>(t, func));
}
public object Build(Type typeToBuild)
{
var obj = funcs.First(f => f.Item1 == typeToBuild).Item2();
//enable property injection
obj.GetType().GetProperties()
.Select(p=>p.PropertyType)
.Intersect(funcs.Select(f=>f.Item1)).ToList()
.ForEach(propertyTypeToSet=>
{
obj.GetType().GetProperties().First(p=>p.PropertyType == propertyTypeToSet)
.SetValue(obj, Build(propertyTypeToSet), null);
});
return obj;
}
public IBuilder CreateChildBuilder()
{
return this;
}
public T Build<T>()
{
return (T)Build(typeof(T));
}
public IEnumerable<T> BuildAll<T>()
{
return funcs.Where(f => f.Item1 == typeof(T))
.Select(f => (T)f.Item2())
.ToList();
}
public IEnumerable<object> BuildAll(Type typeToBuild)
{
return funcs.Where(f => f.Item1 == typeToBuild)
.Select(f => f.Item2())
.ToList();
}
public void BuildAndDispatch(Type typeToBuild, Action<object> action)
{
var obj = Build(typeToBuild);
action(obj);
}
}
}