This repository has been archived by the owner on Jan 24, 2021. It is now read-only.
/
TinyIoC.cs
executable file
·3909 lines (3395 loc) · 165 KB
/
TinyIoC.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===============================================================================
// TinyIoC
//
// An easy to use, hassle free, Inversion of Control Container for small projects
// and beginners alike.
//
// https://github.com/grumpydev/TinyIoC
//===============================================================================
// Copyright © Steven Robbins. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
#region Preprocessor Directives
// Uncomment this line if you want the container to automatically
// register the TinyMessenger messenger/event aggregator
//#define TINYMESSENGER
// Preprocessor directives for enabling/disabling functionality
// depending on platform features. If the platform has an appropriate
// #DEFINE then these should be set automatically below.
#define EXPRESSIONS // Platform supports System.Linq.Expressions
#define COMPILED_EXPRESSIONS // Platform supports compiling expressions
#define APPDOMAIN_GETASSEMBLIES // Platform supports getting all assemblies from the AppDomain object
#define UNBOUND_GENERICS_GETCONSTRUCTORS // Platform supports GetConstructors on unbound generic types
#define GETPARAMETERS_OPEN_GENERICS // Platform supports GetParameters on open generics
#define RESOLVE_OPEN_GENERICS // Platform supports resolving open generics
#define READER_WRITER_LOCK_SLIM // Platform supports ReaderWriterLockSlim
//// NETFX_CORE
//#if NETFX_CORE
//#endif
// CompactFramework / Windows Phone 7
// By default does not support System.Linq.Expressions.
// AppDomain object does not support enumerating all assemblies in the app domain.
#if PocketPC || WINDOWS_PHONE
#undef EXPRESSIONS
#undef COMPILED_EXPRESSIONS
#undef APPDOMAIN_GETASSEMBLIES
#undef UNBOUND_GENERICS_GETCONSTRUCTORS
#endif
// PocketPC has a bizarre limitation on enumerating parameters on unbound generic methods.
// We need to use a slower workaround in that case.
#if PocketPC
#undef GETPARAMETERS_OPEN_GENERICS
#undef RESOLVE_OPEN_GENERICS
#undef READER_WRITER_LOCK_SLIM
#endif
#if SILVERLIGHT
#undef APPDOMAIN_GETASSEMBLIES
#endif
#if NETFX_CORE
#undef APPDOMAIN_GETASSEMBLIES
#undef RESOLVE_OPEN_GENERICS
#endif
#if COMPILED_EXPRESSIONS
#define USE_OBJECT_CONSTRUCTOR
#endif
#endregion
namespace Nancy.TinyIoc
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
#if EXPRESSIONS
using System.Linq.Expressions;
using System.Threading;
#endif
#if NETFX_CORE
using System.Threading.Tasks;
using Windows.Storage.Search;
using Windows.Storage;
using Windows.UI.Xaml.Shapes;
#endif
#region SafeDictionary
#if READER_WRITER_LOCK_SLIM
public class SafeDictionary<TKey, TValue> : IDisposable
{
private readonly ReaderWriterLockSlim _padlock = new ReaderWriterLockSlim();
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
set
{
_padlock.EnterWriteLock();
try
{
TValue current;
if (_Dictionary.TryGetValue(key, out current))
{
var disposable = current as IDisposable;
if (disposable != null)
disposable.Dispose();
}
_Dictionary[key] = value;
}
finally
{
_padlock.ExitWriteLock();
}
}
}
public bool TryGetValue(TKey key, out TValue value)
{
_padlock.EnterReadLock();
try
{
return _Dictionary.TryGetValue(key, out value);
}
finally
{
_padlock.ExitReadLock();
}
}
public bool Remove(TKey key)
{
_padlock.EnterWriteLock();
try
{
return _Dictionary.Remove(key);
}
finally
{
_padlock.ExitWriteLock();
}
}
public void Clear()
{
_padlock.EnterWriteLock();
try
{
_Dictionary.Clear();
}
finally
{
_padlock.ExitWriteLock();
}
}
public IEnumerable<TKey> Keys
{
get
{
_padlock.EnterReadLock();
try
{
return new List<TKey>(_Dictionary.Keys);
}
finally
{
_padlock.ExitReadLock();
}
}
}
#region IDisposable Members
public void Dispose()
{
_padlock.EnterWriteLock();
try
{
var disposableItems = from item in _Dictionary.Values
where item is IDisposable
select item as IDisposable;
foreach (var item in disposableItems)
{
item.Dispose();
}
}
finally
{
_padlock.ExitWriteLock();
}
GC.SuppressFinalize(this);
}
#endregion
}
#else
public class SafeDictionary<TKey, TValue> : IDisposable
{
private readonly object _Padlock = new object();
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
set
{
lock (_Padlock)
{
TValue current;
if (_Dictionary.TryGetValue(key, out current))
{
var disposable = current as IDisposable;
if (disposable != null)
disposable.Dispose();
}
_Dictionary[key] = value;
}
}
}
public bool TryGetValue(TKey key, out TValue value)
{
lock (_Padlock)
{
return _Dictionary.TryGetValue(key, out value);
}
}
public bool Remove(TKey key)
{
lock (_Padlock)
{
return _Dictionary.Remove(key);
}
}
public void Clear()
{
lock (_Padlock)
{
_Dictionary.Clear();
}
}
public IEnumerable<TKey> Keys
{
get
{
return _Dictionary.Keys;
}
}
#region IDisposable Members
public void Dispose()
{
lock (_Padlock)
{
var disposableItems = from item in _Dictionary.Values
where item is IDisposable
select item as IDisposable;
foreach (var item in disposableItems)
{
item.Dispose();
}
}
GC.SuppressFinalize(this);
}
#endregion
}
#endif
#endregion
#region Extensions
public static class AssemblyExtensions
{
public static Type[] SafeGetTypes(this Assembly assembly)
{
Type[] assemblies;
try
{
assemblies = assembly.GetTypes();
}
catch (System.IO.FileNotFoundException)
{
assemblies = new Type[] { };
}
catch (NotSupportedException)
{
assemblies = new Type[] { };
}
#if !NETFX_CORE
catch (ReflectionTypeLoadException e)
{
assemblies = e.Types.Where(t => t != null).ToArray();
}
#endif
return assemblies;
}
}
public static class TypeExtensions
{
private static SafeDictionary<GenericMethodCacheKey, MethodInfo> _genericMethodCache;
static TypeExtensions()
{
_genericMethodCache = new SafeDictionary<GenericMethodCacheKey, MethodInfo>();
}
//#if NETFX_CORE
// /// <summary>
// /// Gets a generic method from a type given the method name, generic types and parameter types
// /// </summary>
// /// <param name="sourceType">Source type</param>
// /// <param name="methodName">Name of the method</param>
// /// <param name="genericTypes">Generic types to use to make the method generic</param>
// /// <param name="parameterTypes">Method parameters</param>
// /// <returns>MethodInfo or null if no matches found</returns>
// /// <exception cref="System.Reflection.AmbiguousMatchException"/>
// /// <exception cref="System.ArgumentException"/>
// public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)
// {
// MethodInfo method;
// var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);
// // Shouldn't need any additional locking
// // we don't care if we do the method info generation
// // more than once before it gets cached.
// if (!_genericMethodCache.TryGetValue(cacheKey, out method))
// {
// method = GetMethod(sourceType, methodName, genericTypes, parameterTypes);
// _genericMethodCache[cacheKey] = method;
// }
// return method;
// }
//#else
/// <summary>
/// Gets a generic method from a type given the method name, binding flags, generic types and parameter types
/// </summary>
/// <param name="sourceType">Source type</param>
/// <param name="bindingFlags">Binding flags</param>
/// <param name="methodName">Name of the method</param>
/// <param name="genericTypes">Generic types to use to make the method generic</param>
/// <param name="parameterTypes">Method parameters</param>
/// <returns>MethodInfo or null if no matches found</returns>
/// <exception cref="System.Reflection.AmbiguousMatchException"/>
/// <exception cref="System.ArgumentException"/>
public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
MethodInfo method;
var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);
// Shouldn't need any additional locking
// we don't care if we do the method info generation
// more than once before it gets cached.
if (!_genericMethodCache.TryGetValue(cacheKey, out method))
{
method = GetMethod(sourceType, bindingFlags, methodName, genericTypes, parameterTypes);
_genericMethodCache[cacheKey] = method;
}
return method;
}
//#endif
#if NETFX_CORE
private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
var methods =
sourceType.GetMethods(flags).Where(
mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(
mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).
Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(
mi => mi.MakeGenericMethod(genericTypes)).Where(
mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();
if (methods.Count > 1)
{
throw new AmbiguousMatchException();
}
return methods.FirstOrDefault();
}
#else
private static MethodInfo GetMethod(Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
#if GETPARAMETERS_OPEN_GENERICS
var methods =
sourceType.GetMethods(bindingFlags).Where(
mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(
mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).
Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(
mi => mi.MakeGenericMethod(genericTypes)).Where(
mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();
#else
var validMethods = from method in sourceType.GetMethods(bindingFlags)
where method.Name == methodName
where method.IsGenericMethod
where method.GetGenericArguments().Length == genericTypes.Length
let genericMethod = method.MakeGenericMethod(genericTypes)
where genericMethod.GetParameters().Count() == parameterTypes.Length
where genericMethod.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)
select genericMethod;
var methods = validMethods.ToList();
#endif
if (methods.Count > 1)
{
throw new AmbiguousMatchException();
}
return methods.FirstOrDefault();
}
#endif
private sealed class GenericMethodCacheKey
{
private readonly Type _sourceType;
private readonly string _methodName;
private readonly Type[] _genericTypes;
private readonly Type[] _parameterTypes;
private readonly int _hashCode;
public GenericMethodCacheKey(Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)
{
_sourceType = sourceType;
_methodName = methodName;
_genericTypes = genericTypes;
_parameterTypes = parameterTypes;
_hashCode = GenerateHashCode();
}
public override bool Equals(object obj)
{
var cacheKey = obj as GenericMethodCacheKey;
if (cacheKey == null)
return false;
if (_sourceType != cacheKey._sourceType)
return false;
if (!String.Equals(_methodName, cacheKey._methodName, StringComparison.Ordinal))
return false;
if (_genericTypes.Length != cacheKey._genericTypes.Length)
return false;
if (_parameterTypes.Length != cacheKey._parameterTypes.Length)
return false;
for (int i = 0; i < _genericTypes.Length; ++i)
{
if (_genericTypes[i] != cacheKey._genericTypes[i])
return false;
}
for (int i = 0; i < _parameterTypes.Length; ++i)
{
if (_parameterTypes[i] != cacheKey._parameterTypes[i])
return false;
}
return true;
}
public override int GetHashCode()
{
return _hashCode;
}
private int GenerateHashCode()
{
unchecked
{
var result = _sourceType.GetHashCode();
result = (result * 397) ^ _methodName.GetHashCode();
for (int i = 0; i < _genericTypes.Length; ++i)
{
result = (result * 397) ^ _genericTypes[i].GetHashCode();
}
for (int i = 0; i < _parameterTypes.Length; ++i)
{
result = (result * 397) ^ _parameterTypes[i].GetHashCode();
}
return result;
}
}
}
}
// @mbrit - 2012-05-22 - shim for ForEach call on List<T>...
#if NETFX_CORE
internal static class ListExtender
{
internal static void ForEach<T>(this List<T> list, Action<T> callback)
{
foreach (T obj in list)
callback(obj);
}
}
#endif
#endregion
#region TinyIoC Exception Types
public class TinyIoCResolutionException : Exception
{
private const string ERROR_TEXT = "Unable to resolve type: {0}";
public TinyIoCResolutionException(Type type)
: base(String.Format(ERROR_TEXT, type.FullName))
{
}
public TinyIoCResolutionException(Type type, Exception innerException)
: base(String.Format(ERROR_TEXT, type.FullName), innerException)
{
}
}
public class TinyIoCRegistrationTypeException : Exception
{
private const string REGISTER_ERROR_TEXT = "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}.";
public TinyIoCRegistrationTypeException(Type type, string factory)
: base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory))
{
}
public TinyIoCRegistrationTypeException(Type type, string factory, Exception innerException)
: base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory), innerException)
{
}
}
public class TinyIoCRegistrationException : Exception
{
private const string CONVERT_ERROR_TEXT = "Cannot convert current registration of {0} to {1}";
private const string GENERIC_CONSTRAINT_ERROR_TEXT = "Type {1} is not valid for a registration of type {0}";
public TinyIoCRegistrationException(Type type, string method)
: base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method))
{
}
public TinyIoCRegistrationException(Type type, string method, Exception innerException)
: base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method), innerException)
{
}
public TinyIoCRegistrationException(Type registerType, Type implementationType)
: base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName))
{
}
public TinyIoCRegistrationException(Type registerType, Type implementationType, Exception innerException)
: base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName), innerException)
{
}
}
public class TinyIoCWeakReferenceException : Exception
{
private const string ERROR_TEXT = "Unable to instantiate {0} - referenced object has been reclaimed";
public TinyIoCWeakReferenceException(Type type)
: base(String.Format(ERROR_TEXT, type.FullName))
{
}
public TinyIoCWeakReferenceException(Type type, Exception innerException)
: base(String.Format(ERROR_TEXT, type.FullName), innerException)
{
}
}
public class TinyIoCConstructorResolutionException : Exception
{
private const string ERROR_TEXT = "Unable to resolve constructor for {0} using provided Expression.";
public TinyIoCConstructorResolutionException(Type type)
: base(String.Format(ERROR_TEXT, type.FullName))
{
}
public TinyIoCConstructorResolutionException(Type type, Exception innerException)
: base(String.Format(ERROR_TEXT, type.FullName), innerException)
{
}
public TinyIoCConstructorResolutionException(string message, Exception innerException)
: base(message, innerException)
{
}
public TinyIoCConstructorResolutionException(string message)
: base(message)
{
}
}
public class TinyIoCAutoRegistrationException : Exception
{
private const string ERROR_TEXT = "Duplicate implementation of type {0} found ({1}).";
public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types)
: base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)))
{
}
public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types, Exception innerException)
: base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)), innerException)
{
}
private static string GetTypesString(IEnumerable<Type> types)
{
var typeNames = from type in types
select type.FullName;
return string.Join(",", typeNames.ToArray());
}
}
#endregion
#region Public Setup / Settings Classes
/// <summary>
/// Name/Value pairs for specifying "user" parameters when resolving
/// </summary>
public sealed class NamedParameterOverloads : Dictionary<string, object>
{
public static NamedParameterOverloads FromIDictionary(IDictionary<string, object> data)
{
return data as NamedParameterOverloads ?? new NamedParameterOverloads(data);
}
public NamedParameterOverloads()
{
}
public NamedParameterOverloads(IDictionary<string, object> data)
: base(data)
{
}
private static readonly NamedParameterOverloads _Default = new NamedParameterOverloads();
public static NamedParameterOverloads Default
{
get
{
return _Default;
}
}
}
public enum UnregisteredResolutionActions
{
/// <summary>
/// Attempt to resolve type, even if the type isn't registered.
///
/// Registered types/options will always take precedence.
/// </summary>
AttemptResolve,
/// <summary>
/// Fail resolution if type not explicitly registered
/// </summary>
Fail,
/// <summary>
/// Attempt to resolve unregistered type if requested type is generic
/// and no registration exists for the specific generic parameters used.
///
/// Registered types/options will always take precedence.
/// </summary>
GenericsOnly
}
public enum NamedResolutionFailureActions
{
AttemptUnnamedResolution,
Fail
}
public enum DuplicateImplementationActions
{
RegisterSingle,
RegisterMultiple,
Fail
}
/// <summary>
/// Resolution settings
/// </summary>
public sealed class ResolveOptions
{
private static readonly ResolveOptions _Default = new ResolveOptions();
private static readonly ResolveOptions _FailUnregisteredAndNameNotFound = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };
private static readonly ResolveOptions _FailUnregisteredOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.AttemptUnnamedResolution, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };
private static readonly ResolveOptions _FailNameNotFoundOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve };
private UnregisteredResolutionActions _UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve;
public UnregisteredResolutionActions UnregisteredResolutionAction
{
get { return _UnregisteredResolutionAction; }
set { _UnregisteredResolutionAction = value; }
}
private NamedResolutionFailureActions _NamedResolutionFailureAction = NamedResolutionFailureActions.Fail;
public NamedResolutionFailureActions NamedResolutionFailureAction
{
get { return _NamedResolutionFailureAction; }
set { _NamedResolutionFailureAction = value; }
}
/// <summary>
/// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found)
/// </summary>
public static ResolveOptions Default
{
get
{
return _Default;
}
}
/// <summary>
/// Preconfigured option for attempting resolution of unregistered types and failing on named resolution if name not found
/// </summary>
public static ResolveOptions FailNameNotFoundOnly
{
get
{
return _FailNameNotFoundOnly;
}
}
/// <summary>
/// Preconfigured option for failing on resolving unregistered types and on named resolution if name not found
/// </summary>
public static ResolveOptions FailUnregisteredAndNameNotFound
{
get
{
return _FailUnregisteredAndNameNotFound;
}
}
/// <summary>
/// Preconfigured option for failing on resolving unregistered types, but attempting unnamed resolution if name not found
/// </summary>
public static ResolveOptions FailUnregisteredOnly
{
get
{
return _FailUnregisteredOnly;
}
}
}
#endregion
public sealed partial class TinyIoCContainer : IDisposable
{
#region Fake NETFX_CORE Classes
#if NETFX_CORE
private sealed class MethodAccessException : Exception
{
}
private sealed class AppDomain
{
public static AppDomain CurrentDomain { get; private set; }
static AppDomain()
{
CurrentDomain = new AppDomain();
}
// @mbrit - 2012-05-30 - in WinRT, this should be done async...
public async Task<List<Assembly>> GetAssembliesAsync()
{
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
List<Assembly> assemblies = new List<Assembly>();
var files = await folder.GetFilesAsync();
foreach (StorageFile file in files)
{
if (file.FileType == ".dll" || file.FileType == ".exe")
{
AssemblyName name = new AssemblyName() { Name = System.IO.Path.GetFileNameWithoutExtension(file.Name) };
try
{
var asm = Assembly.Load(name);
assemblies.Add(asm);
}
catch
{
// ignore exceptions here...
}
}
}
return assemblies;
}
}
#endif
#endregion
#region "Fluent" API
/// <summary>
/// Registration options for "fluent" API
/// </summary>
public sealed class RegisterOptions
{
private TinyIoCContainer _Container;
private TypeRegistration _Registration;
public RegisterOptions(TinyIoCContainer container, TypeRegistration registration)
{
_Container = container;
_Registration = registration;
}
/// <summary>
/// Make registration a singleton (single instance) if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions AsSingleton()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "singleton");
return _Container.AddUpdateRegistration(_Registration, currentFactory.SingletonVariant);
}
/// <summary>
/// Make registration multi-instance if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions AsMultiInstance()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "multi-instance");
return _Container.AddUpdateRegistration(_Registration, currentFactory.MultiInstanceVariant);
}
/// <summary>
/// Make registration hold a weak reference if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions WithWeakReference()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "weak reference");
return _Container.AddUpdateRegistration(_Registration, currentFactory.WeakReferenceVariant);
}
/// <summary>
/// Make registration hold a strong reference if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public RegisterOptions WithStrongReference()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "strong reference");
return _Container.AddUpdateRegistration(_Registration, currentFactory.StrongReferenceVariant);
}
#if EXPRESSIONS
public RegisterOptions UsingConstructor<RegisterType>(Expression<Func<RegisterType>> constructor)
{
var lambda = constructor as LambdaExpression;
if (lambda == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
var newExpression = lambda.Body as NewExpression;
if (newExpression == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
var constructorInfo = newExpression.Constructor;
if (constructorInfo == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
currentFactory.SetConstructor(constructorInfo);
return this;
}
#endif
/// <summary>
/// Switches to a custom lifetime manager factory if possible.
///
/// Usually used for RegisterOptions "To*" extension methods such as the ASP.Net per-request one.
/// </summary>
/// <param name="instance">RegisterOptions instance</param>
/// <param name="lifetimeProvider">Custom lifetime manager</param>
/// <param name="errorString">Error string to display if switch fails</param>
/// <returns>RegisterOptions</returns>
public static RegisterOptions ToCustomLifetimeManager(RegisterOptions instance, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
{
if (instance == null)
throw new ArgumentNullException("instance", "instance is null.");
if (lifetimeProvider == null)
throw new ArgumentNullException("lifetimeProvider", "lifetimeProvider is null.");
if (String.IsNullOrEmpty(errorString))
throw new ArgumentException("errorString is null or empty.", "errorString");
var currentFactory = instance._Container.GetCurrentFactory(instance._Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(instance._Registration.Type, errorString);
return instance._Container.AddUpdateRegistration(instance._Registration, currentFactory.GetCustomObjectLifetimeVariant(lifetimeProvider, errorString));
}
}
/// <summary>
/// Registration options for "fluent" API when registering multiple implementations
/// </summary>
public sealed class MultiRegisterOptions
{
private IEnumerable<RegisterOptions> _RegisterOptions;
/// <summary>
/// Initializes a new instance of the MultiRegisterOptions class.
/// </summary>
/// <param name="registerOptions">Registration options</param>
public MultiRegisterOptions(IEnumerable<RegisterOptions> registerOptions)
{
_RegisterOptions = registerOptions;
}
/// <summary>
/// Make registration a singleton (single instance) if possible
/// </summary>
/// <returns>RegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public MultiRegisterOptions AsSingleton()
{
_RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton());
return this;
}
/// <summary>
/// Make registration multi-instance if possible
/// </summary>
/// <returns>MultiRegisterOptions</returns>
/// <exception cref="TinyIoCInstantiationTypeException"></exception>
public MultiRegisterOptions AsMultiInstance()
{
_RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance());
return this;
}