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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Tango.Core.DI
{
/// <summary>
/// Represents the default Tango IOC container.
/// </summary>
/// <seealso cref="Tango.Core.DI.ITangoIOC" />
public class TangoIOC : ExtendedObject, ITangoIOC
{
private class RegisteredType
{
public Type InterfaceType { get; set; }
public Type ImplementationType { get; set; }
public Object Instance { get; set; }
public RegisteredType(Type interfaceType, Type implementationType, Object instance)
{
InterfaceType = interfaceType;
ImplementationType = implementationType;
Instance = instance;
}
}
private static TangoIOC _default;
/// <summary>
/// Gets the default Tango IOC container instance.
/// </summary>
public static TangoIOC Default
{
get
{
if (_default == null)
{
_default = new TangoIOC();
}
return _default;
}
}
private Dictionary<Type, RegisteredType> _registeredTypes;
private List<Tuple<Type, Action<Object>>> _waitingRetrivals;
/// <summary>
/// Gets or sets a value indicating whether to throw an exception when a type is requested but not registered.
/// </summary>
public bool ThrowOnRequestedTypeNotFound { get; set; } = true;
/// <summary>
/// Initializes a new instance of the <see cref="TangoIOC"/> class.
/// </summary>
public TangoIOC()
{
_registeredTypes = new Dictionary<Type, RegisteredType>();
_waitingRetrivals = new List<Tuple<Type, Action<object>>>();
}
/// <summary>
/// Registers the specified type.
/// </summary>
/// <typeparam name="T"></typeparam>
public void Register<T>() where T : class
{
RegisterInternal(typeof(T), typeof(T), null);
}
/// <summary>
/// Registers the specified instance type and instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">The instance.</param>
public void Register<T>(T instance) where T : class
{
RegisterInternal(typeof(T), instance.GetType(), instance);
}
/// <summary>
/// Registers the specified type.
/// </summary>
/// <param name="type">The type.</param>
public void Register(Type type)
{
RegisterInternal(type, type, null);
}
/// <summary>
/// Registers the specified type and implementation type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="implementation">The implementation.</param>
public void Register(Type type, Type implementation)
{
RegisterInternal(type, implementation.GetType(), null);
}
/// <summary>
/// Registers the specified type and instance.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="instance">The instance.</param>
public void Register(Type type, Object instance)
{
RegisterInternal(type, instance.GetType(), instance);
}
/// <summary>
/// Registers this instance.
/// </summary>
/// <typeparam name="Type">The type of the type.</typeparam>
/// <typeparam name="Implementation">The type of the implementation.</typeparam>
public void Register<Type, Implementation>() where Implementation : class, Type
{
RegisterInternal(typeof(Type), typeof(Implementation), null);
}
/// <summary>
/// Registers the specified type, implementation and implementation instance.
/// </summary>
/// <typeparam name="Type">The type of the type.</typeparam>
/// <typeparam name="Implementation">The type of the implementation.</typeparam>
/// <param name="instance">The instance.</param>
public void Register<Type, Implementation>(Implementation instance) where Implementation : class, Type
{
RegisterInternal(typeof(Type), typeof(Implementation), instance);
}
/// <summary>
/// Unregisters the specified type.
/// </summary>
/// <typeparam name="T"></typeparam>
public void Unregister<T>()
{
Unregister(typeof(T));
}
/// <summary>
/// Unregisters the specified type.
/// </summary>
/// <param name="type">The type.</param>
public virtual void Unregister(Type type)
{
_registeredTypes.Remove(type);
}
/// <summary>
/// Gets the instance of type T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetInstance<T>()
{
return (T)GetInstance(typeof(T));
}
/// <summary>
/// Notifies the awaiting retrievals of a new instance available.
/// </summary>
/// <param name="registeredType">Type of the registered.</param>
private void NotifyAwaitingRetrievals(RegisteredType registeredType)
{
var toNotify = _waitingRetrivals.Where(x => x.Item1 == registeredType.InterfaceType).ToList();
toNotify.ForEach(x => x.Item2(registeredType.Instance));
_waitingRetrivals.RemoveAll(x => toNotify.Contains(x));
}
/// <summary>
/// Gets the instance by the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
/// <exception cref="System.InvalidOperationException">The type specified could not be located!</exception>
public virtual object GetInstance(Type type)
{
RegisteredType registeredType = null;
if (_registeredTypes.TryGetValue(type, out registeredType))
{
if (registeredType.Instance == null)
{
registeredType.Instance = CreateInstance(registeredType.ImplementationType);
NotifyAwaitingRetrievals(registeredType);
}
return registeredType.Instance;
}
else
{
//Try get by inherited..
registeredType = _registeredTypes.Select(x => x.Value).SingleOrDefault(x => type.IsAssignableFrom(x.InterfaceType));
if (registeredType != null)
{
if (registeredType.Instance == null)
{
registeredType.Instance = CreateInstance(registeredType.ImplementationType);
NotifyAwaitingRetrievals(registeredType);
}
return registeredType.Instance;
}
if (!DesignMode && ThrowOnRequestedTypeNotFound)
{
throw new InvalidOperationException(String.Format("Requested type '{0}' could not be found.", type.Name));
}
else
{
return null;
}
}
}
/// <summary>
/// Executes the specified action when type T is available. if already available action will be executed immediately.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="callback">The callback.</param>
/// <returns></returns>
public void GetInstanceWhenAvailable<T>(Action<T> callback)
{
GetInstanceWhenAvailable(typeof(T), (x) => callback((T)x));
}
/// <summary>
/// Executes the specified action when type T is available. if already available action will be executed immediately.
/// </summary>
/// <param name="callback">The callback.</param>
/// <returns></returns>
public virtual void GetInstanceWhenAvailable(Type type, Action<object> callback)
{
RegisteredType registeredType = null;
if (_registeredTypes.TryGetValue(type, out registeredType))
{
if (registeredType.Instance != null)
{
callback(registeredType.Instance);
return;
}
}
else
{
//Try get by inherited..
registeredType = _registeredTypes.Select(x => x.Value).SingleOrDefault(x => type.IsAssignableFrom(x.InterfaceType));
if (registeredType != null)
{
if (registeredType.Instance != null)
{
callback(registeredType.Instance);
return;
}
}
}
_waitingRetrivals.Add(new Tuple<Type, Action<object>>(type, callback));
}
/// <summary>
/// Determines whether the specified type is registered.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>
/// <c>true</c> if this instance is registered; otherwise, <c>false</c>.
/// </returns>
public bool IsRegistered<T>()
{
return IsRegistered(typeof(T));
}
/// <summary>
/// Determines whether the specified type is registered.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the specified type is registered; otherwise, <c>false</c>.
/// </returns>
public virtual bool IsRegistered(Type type)
{
return _registeredTypes.ContainsKey(type);
}
/// <summary>
/// Registers the internal.
/// </summary>
/// <param name="interfaceType">Type of the interface.</param>
/// <param name="implementationType">Type of the implementation.</param>
/// <param name="instance">The instance.</param>
protected virtual void RegisterInternal(Type interfaceType, Type implementationType, Object instance)
{
if (DesignMode)
{
return;
}
if (!interfaceType.IsAssignableFrom(implementationType))
{
throw new InvalidOperationException(String.Format("Interface type '{0}' cannot be assigned from implementation type '{1}'.", interfaceType.Name, implementationType.Name));
}
if (IsRegistered(interfaceType))
{
throw new InvalidOperationException(String.Format("The specified type '{0}' is already registered.", interfaceType.Name));
}
if (instance != null && instance.GetType() != implementationType)
{
throw new InvalidOperationException(String.Format("Instance type '{0}' does not match the implementation type '{1}'.", instance.GetType().Name, implementationType.Name));
}
var registeredType = new RegisteredType(interfaceType, implementationType, instance);
_registeredTypes.Add(interfaceType, registeredType);
if (implementationType.GetCustomAttribute<TangoCreateWhenRegisteredAttribute>() != null && instance == null)
{
instance = GetInstance(interfaceType);
}
if (registeredType.Instance != null)
{
NotifyAwaitingRetrievals(registeredType);
}
}
/// <summary>
/// Initializes the instance.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
protected virtual object CreateInstance(Type type)
{
List<object> arguments = new List<object>();
ConstructorInfo constructor = null;
constructor = type.GetConstructors().FirstOrDefault(x => x.GetCustomAttribute<TangoInjectAttribute>() != null);
if (constructor == null)
{
constructor = type.GetConstructors().FirstOrDefault(x => x.GetParameters().Count() > 0);
}
object instance = null;
if (constructor != null)
{
foreach (var arg in constructor.GetParameters())
{
arguments.Add(GetInstance(arg.ParameterType));
}
instance = Activator.CreateInstance(type, arguments.ToArray());
}
else
{
instance = Activator.CreateInstance(type);
}
Inject(instance);
return instance;
}
/// <summary>
/// Gets all instances by the specified base type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IEnumerable<T> GetAllInstancesByBase<T>()
{
return GetAllInstancesByBase(typeof(T)).Select(x => (T)x);
}
/// <summary>
/// Gets all instances by the specified base type.
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <returns></returns>
public virtual IEnumerable<object> GetAllInstancesByBase(Type baseType)
{
return _registeredTypes.Where(x => baseType.IsAssignableFrom(x.Key)).Select(x => x.Value.Instance != null ? x.Value.Instance : GetInstance(x.Value.ImplementationType));
}
/// <summary>
/// Injects any dependencies to the target properties using the <see cref="TangoInjectAttribute" />.
/// </summary>
/// <param name="target">The target.</param>
public void Inject(object target)
{
var type = target.GetType();
foreach (var prop in type.GetPropertiesWithAttribute<TangoInjectAttribute>(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
var att = prop.GetCustomAttribute<TangoInjectAttribute>();
if (att.Mode == TangoInjectMode.Immediate)
{
prop.SetValue(target, GetInstance(prop.PropertyType));
}
else
{
GetInstanceWhenAvailable(prop.PropertyType, (x) =>
{
prop.SetValue(target, GetInstance(prop.PropertyType));
});
}
}
foreach (var field in type.GetFieldsWithAttribute<TangoInjectAttribute>(BindingFlags.NonPublic | BindingFlags.Instance))
{
var att = field.GetCustomAttribute<TangoInjectAttribute>();
if (att.Mode == TangoInjectMode.Immediate)
{
field.SetValue(target, GetInstance(field.FieldType));
}
else
{
GetInstanceWhenAvailable(field.FieldType, (x) =>
{
field.SetValue(target, GetInstance(field.FieldType));
});
}
}
}
}
}
|