/
SettingsCollection.cs
117 lines (96 loc) · 2.99 KB
/
SettingsCollection.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FubuCore;
using FubuCore.Binding;
using FubuCore.Configuration;
using FubuCore.Util;
using FubuMVC.Core.ServiceBus;
using FubuMVC.Core.ServiceBus.Configuration;
using FubuMVC.Core.ServiceBus.Polling;
using FubuMVC.Core.ServiceBus.ScheduledJobs;
namespace FubuMVC.Core.Registration
{
public class SettingsCollection
{
public static readonly Lazy<ISettingsProvider> SettingsProvider =
new Lazy<ISettingsProvider>(() => new AppSettingsProvider(ObjectResolver.Basic()));
private readonly Cache<Type, object> _settings = new Cache<Type, object>();
public SettingsCollection()
{
_settings.OnMissing = buildDefault;
warmUp<ChannelGraph>();
warmUp<PollingJobSettings>();
warmUp<ScheduledJobGraph>();
warmUp<TransportSettings>();
}
private void warmUp<T>() where T : class
{
Alter<T>(x => { });
}
private static object buildDefault(Type type)
{
return SettingsProvider.Value.SettingsFor(type);
}
public T Get<T>() where T : class
{
return _settings[typeof (T)].As<T>();
}
public void Alter<T>(Action<T> alteration) where T : class
{
alteration(Get<T>());
}
public void Replace<T>(T settings) where T : class
{
_settings[typeof (T)] = settings;
}
public bool HasExplicit<T>()
{
return _settings.Has(typeof (T));
}
public void Register(ServiceRegistry registry)
{
_settings.Each((t, o) =>
{
var registrar = typeof (Registrar<>).CloseAndBuildAs<IRegistrar>(o, t);
registrar.Register(registry);
});
}
public interface IRegistrar
{
void Register(ServiceRegistry registry);
}
public class Registrar<T> : IRegistrar where T : class
{
private readonly T _settings;
public Registrar(T settings)
{
_settings = settings;
}
public void Register(ServiceRegistry registry)
{
registry.For<T>().ClearAll().Use(_settings);
}
}
public object Get(Type type)
{
return _settings[type];
}
}
public static class TaskExtensions
{
public static T Result<T>(this Task<T> task)
{
task.Wait(30.Seconds()).AssertFinished();
return task.Result;
}
public static void AssertFinished(this bool waited)
{
if (!waited)
{
throw new TimeoutException("Task operation timed out");
}
}
}
}