forked from ThatRendle/Simple.Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCachingAdapterFactory.cs
More file actions
55 lines (46 loc) · 1.62 KB
/
CachingAdapterFactory.cs
File metadata and controls
55 lines (46 loc) · 1.62 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Simple.Data
{
class CachingAdapterFactory : AdapterFactory
{
public CachingAdapterFactory()
{
}
public CachingAdapterFactory(Composer composer) : base(composer)
{
}
private readonly ConcurrentDictionary<string, Adapter> _cache = new ConcurrentDictionary<string, Adapter>();
public override Adapter Create(string adapterName, IEnumerable<KeyValuePair<string, object>> settings)
{
List<KeyValuePair<string, object>> mat;
string hash;
if (settings == null)
{
mat = new List<KeyValuePair<string, object>>();
hash = adapterName;
}
else
{
mat = settings.ToList();
hash = HashSettings(adapterName, mat);
}
var adapter = _cache.GetOrAdd(hash, _ => DoCreate(adapterName, mat));
var cloneable = adapter as ICloneable;
if (cloneable != null) return (Adapter)cloneable.Clone();
return adapter;
}
private static string HashSettings(string adapterName, IEnumerable<KeyValuePair<string, object>> settings)
{
return adapterName +
string.Join("#", settings.Select(kvp => kvp.Key + "=" + kvp.Value));
}
public void Reset()
{
_cache.Clear();
}
}
}