/
TinyIoC.cs
3109 lines (2714 loc) · 135 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.
//
// http://hg.grumpydev.com/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.
//===============================================================================
// -- MONOTOUCH IMPORTANT -- //
// If you are intending to use MonoTouch you *must* define MONOTOUCH or the code
// will not compile.
// -- MONOTOUCH IMPORTANT -- //
#define MONOTOUCH
#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 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 ASPNET // Adds ASP.Net pre-request singleton support
// 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 APPDOMAIN_GETASSEMBLIES
#undef UNBOUND_GENERICS_GETCONSTRUCTORS
#undef ASPNET
#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
#endif
#if SILVERLIGHT
#undef APPDOMAIN_GETASSEMBLIES
#undef ASPNET
#endif
#if MONOTOUCH
#undef ASPNET
#endif
#endregion
namespace TinyIoC
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if EXPRESSIONS
using System.Linq.Expressions;
#endif
#if ASPNET
using System.Web;
#endif
#region SafeDictionary
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
}
#endregion
#region Extensions
public static class TypeExtensions
{
/// <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, System.Reflection.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.InvariantCulture))
.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();
var actualMethod = methods.FirstOrDefault();
return actualMethod;
}
}
#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
}
/// <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 class TinyIoCContainer : IDisposable
{
#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);
}
#if ASPNET
public RegisterOptions AsPerRequestSingleton()
{
var currentFactory = _Container.GetCurrentFactory(_Registration);
if (currentFactory == null)
throw new TinyIoCRegistrationException(_Registration.Type, "singleton");
return _Container.AddUpdateRegistration(_Registration, currentFactory.PerRequestSingletonVariant);
}
#endif
/// <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>
/// 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;
}
private IEnumerable<RegisterOptions> ExecuteOnAllRegisterOptions(Func<RegisterOptions, RegisterOptions> action)
{
var newRegisterOptions = new List<RegisterOptions>();
foreach (var registerOption in _RegisterOptions)
{
newRegisterOptions.Add(action(registerOption));
}
return newRegisterOptions;
}
}
#endregion
#region Public API
#region Child Containers
public TinyIoCContainer GetChildContainer()
{
return new TinyIoCContainer(this);
}
#endregion
#region Registration
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
public void AutoRegister()
{
#if APPDOMAIN_GETASSEMBLIES
AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), true);
#else
AutoRegisterInternal(new Assembly[] {this.GetType().Assembly}, true);
#endif
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
/// </summary>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(bool ignoreDuplicateImplementations)
{
#if APPDOMAIN_GETASSEMBLIES
AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), ignoreDuplicateImplementations);
#else
AutoRegisterInternal(new Assembly[] { this.GetType().Assembly }, ignoreDuplicateImplementations);
#endif
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assembly
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
/// <param name="assembly">Assembly to process</param>
public void AutoRegister(Assembly assembly)
{
AutoRegisterInternal(new Assembly[] { assembly }, true);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assembly
/// </summary>
/// <param name="assembly">Assembly to process</param>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(Assembly assembly, bool ignoreDuplicateImplementations)
{
AutoRegisterInternal(new Assembly[] { assembly }, ignoreDuplicateImplementations);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
///
/// If more than one class implements an interface then only one implementation will be registered
/// although no error will be thrown.
/// </summary>
/// <param name="assemblies">Assemblies to process</param>
public void AutoRegister(IEnumerable<Assembly> assemblies)
{
AutoRegisterInternal(assemblies, true);
}
/// <summary>
/// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
/// </summary>
/// <param name="assemblies">Assemblies to process</param>
/// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param>
/// <exception cref="TinyIoCAutoRegistrationException"/>
public void AutoRegister(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations)
{
AutoRegisterInternal(assemblies, ignoreDuplicateImplementations);
}
/// <summary>
/// Creates/replaces a container class registration with default options.
/// </summary>
/// <param name="registerImplementation">Type to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerImplementation)
{
return ExecuteGenericRegister(new Type[] { registerImplementation }, new Type[] { }, null);
}
/// <summary>
/// Creates/replaces a named container class registration with default options.
/// </summary>
/// <param name="registerImplementation">Type to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerImplementation, string name)
{
return ExecuteGenericRegister(new Type[] { registerImplementation }, new Type[] { typeof(string) }, new object[] { name });
}
/// <summary>
/// Creates/replaces a container class registration with a given implementation and default options.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type to instantiate that implements RegisterType</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation)
{
return ExecuteGenericRegister(new Type[] { registerType, registerImplementation }, new Type[] { }, null);
}
/// <summary>
/// Creates/replaces a named container class registration with a given implementation and default options.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type to instantiate that implements RegisterType</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation, string name)
{
return ExecuteGenericRegister(new Type[] { registerType, registerImplementation }, new Type[] { typeof(string) }, new object[] { name });
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerImplementation">Type to register</param>
/// <param name="instance">Instance of RegisterType to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerImplementation, object instance)
{
return ExecuteGenericRegister(new Type[] { registerImplementation }, new Type[] { registerImplementation }, new object[] { instance });
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerImplementation">Type to register</param>
/// <param name="instance">Instance of RegisterType to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerImplementation, object instance, string name)
{
return ExecuteGenericRegister(new Type[] { registerImplementation }, new Type[] { registerImplementation, typeof(string) }, new object[] { instance, name });
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type of instance to register that implements RegisterType</param>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type implementationType, object instance)
{
return ExecuteGenericRegister(new Type[] { registerType, implementationType }, new Type[] { implementationType }, new object[] { instance });
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register</param>
/// <param name="registerImplementation">Type of instance to register that implements RegisterType</param>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register(Type registerType, Type implementationType, object instance, string name)
{
return ExecuteGenericRegister(new Type[] { registerType, implementationType }, new Type[] { implementationType, typeof(string) }, new object[] { instance, name });
}
/// <summary>
/// Creates/replaces a container class registration with default options.
/// </summary>
/// <typeparam name="RegisterImplementation">Type to register</typeparam>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>()
where RegisterType : class
{
return RegisterInternal(typeof(RegisterType), string.Empty, GetDefaultObjectFactory<RegisterType, RegisterType>());
}
/// <summary>
/// Creates/replaces a named container class registration with default options.
/// </summary>
/// <typeparam name="RegisterImplementation">Type to register</typeparam>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(string name)
where RegisterType : class
{
return RegisterInternal(typeof(RegisterType), name, GetDefaultObjectFactory<RegisterType, RegisterType>());
}
/// <summary>
/// Creates/replaces a container class registration with a given implementation and default options.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type to instantiate that implements RegisterType</typeparam>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>()
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return RegisterInternal(typeof(RegisterType), string.Empty, GetDefaultObjectFactory<RegisterType, RegisterImplementation>());
}
/// <summary>
/// Creates/replaces a named container class registration with a given implementation and default options.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type to instantiate that implements RegisterType</typeparam>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>(string name)
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return RegisterInternal(typeof(RegisterType), name, GetDefaultObjectFactory<RegisterType, RegisterImplementation>());
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterImplementation">Type to register</typeparam>
/// <param name="instance">Instance of RegisterType to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(RegisterType instance)
where RegisterType : class
{
return RegisterInternal(typeof(RegisterType), string.Empty, new InstanceFactory<RegisterType, RegisterType>(instance));
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterImplementation">Type to register</typeparam>
/// <param name="instance">Instance of RegisterType to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(RegisterType instance, string name)
where RegisterType : class
{
return RegisterInternal(typeof(RegisterType), name, new InstanceFactory<RegisterType, RegisterType>(instance));
}
/// <summary>
/// Creates/replaces a container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type of instance to register that implements RegisterType</typeparam>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance)
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return RegisterInternal(typeof(RegisterType), string.Empty, new InstanceFactory<RegisterType, RegisterImplementation>(instance));
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <typeparam name="RegisterImplementation">Type of instance to register that implements RegisterType</typeparam>
/// <param name="instance">Instance of RegisterImplementation to register</param>
/// <param name="name">Name of registration</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance, string name)
where RegisterType : class
where RegisterImplementation : class, RegisterType
{
return RegisterInternal(typeof(RegisterType), name, new InstanceFactory<RegisterType, RegisterImplementation>(instance));
}
/// <summary>
/// Creates/replaces a container class registration with a user specified factory
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory)
where RegisterType : class
{
return RegisterInternal(typeof(RegisterType), string.Empty, new DelegateFactory<RegisterType>(factory));
}
/// <summary>
/// Creates/replaces a named container class registration with a user specified factory
/// </summary>
/// <typeparam name="RegisterType">Type to register</typeparam>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType</param>
/// <param name="name">Name of registation</param>
/// <returns>RegisterOptions for fluent API</returns>
public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory, string name)
where RegisterType : class
{
return RegisterInternal(typeof(RegisterType), name, new DelegateFactory<RegisterType>(factory));
}
/// <summary>
/// Register multiple implementations of a type.
///
/// Internally this registers each implementation using the full name of the class as its registration name.
/// </summary>
/// <typeparam name="RegisterType">Type that each implementation implements</typeparam>
/// <param name="types">Types that implement RegisterType</param>
/// <returns>MultiRegisterOptions for the fluent API</returns>
public MultiRegisterOptions RegisterMultiple<RegisterType>(IEnumerable<Type> types)
{
if (types == null)
throw new ArgumentNullException("types", "types is null.");
foreach (var type in types)
if (!typeof(RegisterType).IsAssignableFrom(type))
throw new ArgumentException(String.Format("types: The type {0} is not assignable from {1}", typeof(RegisterType).FullName, type.FullName));
if (types.Count() != types.Distinct().Count())
throw new ArgumentException("types: The same implementation type cannot be specificed multiple times");
var registerOptions = new List<RegisterOptions>();
foreach (var type in types)
{
registerOptions.Add(Register(typeof(RegisterType), type, type.FullName));
}
return new MultiRegisterOptions(registerOptions);
}
#endregion
#region Resolution
/// <summary>
/// Attempts to resolve a type using default options.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType)
{
return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve a type using specified options.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="options">Resolution options</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, ResolveOptions options)
{
return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);
}
/// <summary>
/// Attempts to resolve a type using default options and the supplied name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>
/// <param name="name">Name of registration</param>
/// <returns>Instance of type</returns>
/// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception>
public object Resolve(Type resolveType, string name)
{
return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);
}
/// <summary>
/// Attempts to resolve a type using supplied options and name.
///
/// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
/// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
/// </summary>
/// <param name="resolveType">Type to resolve</param>