/
Container.Registration.cs
1254 lines (1176 loc) · 67.9 KB
/
Container.Registration.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
#region Copyright Simple Injector Contributors
/* The Simple Injector is an easy-to-use Inversion of Control library for .NET
*
* Copyright (c) 2013-2015 Simple Injector Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
namespace SimpleInjector
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using SimpleInjector.Advanced;
using SimpleInjector.Lifestyles;
#if !PUBLISH
/// <summary>Methods for registration.</summary>
#endif
public partial class Container
{
/// <summary>
/// Occurs when an instance of a type is requested that has not been registered explicitly, allowing
/// resolution of unregistered types before the container tries to create the type.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ResolveUnregisteredType"/> event is called by the container every time an
/// unregistered type is requested for the first time, allowing a developer to do unregistered type
/// resolution. By calling the
/// <see cref="UnregisteredTypeEventArgs.Register(Registration)">Register</see> method on the
/// <see cref="UnregisteredTypeEventArgs"/>, a <see cref="Registration"/>, <see cref="Expression"/> or
/// <see cref="Func{TResult}"/> delegate can be registered allowing the container to retrieve
/// instances of the requested type. This registration is cached and it prevents the
/// <b>ResolveUnregisteredType</b> event from being called again for the same type.
/// </para>
/// <para>
/// When no registered event handled the registration of an unregistered type, the container will try
/// to create the type when this type is either concrete or is the <see cref="IEnumerable{T}"/>
/// interface. Concrete types will be registered with the <see cref="Lifestyle.Transient">Transient</see>
/// lifestyle and <see cref="IEnumerable{T}"/> registrations will return an empty collection. When no
/// even handled the registration and the container could not create it, an exception is thrown.
/// </para>
/// <para>
/// <b>Thread-safety:</b> Please note that the container will not ensure that the hooked delegates
/// are executed only once. While the calls to <see cref="ResolveUnregisteredType" /> for a given type
/// are finite (and will in most cases happen just once), a container can call the delegate multiple
/// times and make parallel calls to the delegate. You must make sure that the code can be called
/// multiple times and is thread-safe.
/// </para>
/// </remarks>
/// <example>
/// The following example shows the usage of the <see cref="ResolveUnregisteredType" /> event:
/// <code lang="cs"><![CDATA[
/// public interface IValidator<T>
/// {
/// void Validate(T instance);
/// }
///
/// // Implementation of the null object pattern.
/// public class EmptyValidator<T> : IValidator<T>
/// {
/// public void Validate(T instance)
/// {
/// // Does nothing.
/// }
/// }
///
/// [TestMethod]
/// public void TestResolveUnregisteredType()
/// {
/// // Arrange
/// var container = new Container();
///
/// // Register an EmptyValidator<T> to be returned when a IValidator<T> is requested:
/// container.ResolveUnregisteredType += (sender, e) =>
/// {
/// if (e.UnregisteredServiceType.IsGenericType &&
/// e.UnregisteredServiceType.GetGenericTypeDefinition() == typeof(IValidator<>))
/// {
/// var validatorType = typeof(EmptyValidator<>).MakeGenericType(
/// e.UnregisteredServiceType.GetGenericArguments());
///
/// object emptyValidator = container.GetInstance(validatorType);
///
/// // Register the instance as singleton.
/// e.Register(() => emptyValidator);
/// }
/// };
///
/// // Act
/// var orderValidator = container.GetInstance<IValidator<Order>>();
/// var customerValidator = container.GetInstance<IValidator<Customer>>();
///
/// // Assert
/// Assert.IsInstanceOfType(orderValidator, typeof(EmptyValidator<Order>));
/// Assert.IsInstanceOfType(customerValidator, typeof(EmptyValidator<Customer>));
/// }
/// ]]></code>
/// <para>
/// The example above registers a delegate that is raised every time an unregistered type is requested
/// from the container. The delegate checks whether the requested type is a closed generic
/// implementation of the <b>IValidator<T></b> interface (such as
/// <b>IValidator<Order></b> or <b>IValidator<Customer></b>). In that case it
/// will request the container for a concrete <b>EmptyValidator<T></b> implementation that
/// implements the given
/// <see cref="UnregisteredTypeEventArgs.UnregisteredServiceType">UnregisteredServiceType</see>, and
/// registers a delegate that will return this created instance. The <b>e.Register</b> call
/// registers the method in the container, preventing the <see cref="ResolveUnregisteredType"/> from
/// being called again for the exact same service type, preventing any performance penalties.
/// </para>
/// <para>
/// Please note that given example is just an uhhmm... example. In the case of the example the
/// <b>EmptyValidator<T></b> can be better registered using of the built-in
/// <see cref="Register(System.Type, System.Type, Lifestyle)">Register</see> methods instead. These methods take
/// care of any given generic type constraint and allow the implementation to be integrated into the
/// container's pipeline, which allows it to be intercepted using the <see cref="ExpressionBuilding"/>
/// event and allow any registered <see cref="RegisterInitializer{TService}">initializers</see> to be
/// applied.
/// </para>
/// </example>
public event EventHandler<UnregisteredTypeEventArgs> ResolveUnregisteredType
{
add
{
this.ThrowWhenContainerIsLockedOrDisposed();
this.resolveUnregisteredType += value;
}
remove
{
this.ThrowWhenContainerIsLockedOrDisposed();
this.resolveUnregisteredType -= value;
}
}
/// <summary>
/// Occurs after the creation of the <see cref="Expression" /> of a registered type is complete (the
/// lifestyle has been applied), allowing the created <see cref="Expression" /> to be wrapped,
/// changed, or replaced. Multiple delegates may handle the same service type.
/// </summary>
/// <remarks>
/// <para>
/// The <b>ExpressionBuilt</b> event is called by the container every time an registered type is
/// getting compiled, allowing a developer to change the way the type is created. The delegate that
/// hooks to the <b>ExpressionBuilt</b> event, can change the
/// <see cref="ExpressionBuiltEventArgs.Expression" /> property on the
/// <see cref="ExpressionBuiltEventArgs"/>, which allows changing the way the type is constructed.
/// </para>
/// <para>
/// <b>Thread-safety:</b> Please note that the container will not ensure that the hooked delegates
/// are executed only once per service type. While the calls to <see cref="ExpressionBuilt" /> for a
/// given type are finite (and will in most cases happen just once), a container can call the delegate
/// multiple times and make parallel calls to the delegate. You must make sure that the code can be
/// called multiple times and is thread-safe.
/// </para>
/// </remarks>
/// <example>
/// The following example shows the usage of the <b>ExpressionBuilt</b> event:
/// <code lang="cs"><![CDATA[
/// public interface IValidator<T>
/// {
/// void Validate(T instance);
/// }
///
/// public interface ILogger
/// {
/// void Write(string message);
/// }
///
/// // Implementation of the decorator pattern.
/// public class MonitoringValidator<T> : IValidator<T>
/// {
/// private readonly IValidator<T> validator;
/// private readonly ILogger logger;
///
/// public MonitoringValidator(IValidator<T> validator, ILogger logger)
/// {
/// this.validator = validator;
/// this.logger = logger;
/// }
///
/// public void Validate(T instance)
/// {
/// this.logger.Write("Validating " + typeof(T).Name);
/// this.validator.Validate(instance);
/// this.logger.Write("Validated " + typeof(T).Name);
/// }
/// }
///
/// [TestMethod]
/// public void TestExpressionBuilt()
/// {
/// // Arrange
/// var container = new Container();
///
/// container.Register<ILogger, ConsoleLogger>(Lifestyle.Singleton);
/// container.Register<IValidator<Order>, OrderValidator>();
/// container.Register<IValidator<Customer>, CustomerValidator>();
///
/// // Intercept the creation of IValidator<T> instances and wrap them in a MonitoringValidator<T>:
/// container.ExpressionBuilt += (sender, e) =>
/// {
/// if (e.RegisteredServiceType.IsGenericType &&
/// e.RegisteredServiceType.GetGenericTypeDefinition() == typeof(IValidator<>))
/// {
/// var decoratorType = typeof(MonitoringValidator<>)
/// .MakeGenericType(e.RegisteredServiceType.GetGenericArguments());
///
/// // Wrap the IValidator<T> in a MonitoringValidator<T>.
/// e.Expression = Expression.New(decoratorType.GetConstructors()[0], new Expression[]
/// {
/// e.Expression,
/// container.GetRegistration(typeof(ILogger)).BuildExpression(),
/// });
/// }
/// };
///
/// // Act
/// var orderValidator = container.GetInstance<IValidator<Order>>();
/// var customerValidator = container.GetInstance<IValidator<Customer>>();
///
/// // Assert
/// Assert.IsInstanceOfType(orderValidator, typeof(MonitoringValidator<Order>));
/// Assert.IsInstanceOfType(customerValidator, typeof(MonitoringValidator<Customer>));
/// }
/// ]]></code>
/// <para>
/// The example above registers a delegate that is raised every time the container compiles the
/// expression for an registered type. The delegate checks whether the requested type is a closed generic
/// implementation of the <b>IValidator<T></b> interface (such as
/// <b>IValidator<Order></b> or <b>IValidator<Customer></b>). In that case it
/// will changes the current <see cref="ExpressionBuiltEventArgs.Expression"/> with a new one that creates
/// a new <b>MonitoringValidator<T></b> that takes the current validator (and an <b>ILogger</b>)
/// as an dependency.
/// </para>
/// <para>
/// Please note that given example is just an uhhmm... example. In the case of the example the
/// <b>MonitoringValidator<T></b> is a decorator and instead of manually writing this code that
/// many limitations, you can use one of the built-in
/// <see cref="Container.RegisterDecorator(System.Type, System.Type, Lifestyle)">RegisterDecorator</see> methods instead.
/// These extension methods take care of any given generic type constraint, allow to register decorators
/// conditionally and allow the decorator to be integrated into the container's pipeline, which allows
/// it to be intercepted using the <see cref="ExpressionBuilding"/> event and allow any registered
/// <see cref="RegisterInitializer{TService}">initializers</see> to be applied.
/// </para>
/// </example>
public event EventHandler<ExpressionBuiltEventArgs> ExpressionBuilt
{
add
{
this.ThrowWhenContainerIsLockedOrDisposed();
this.expressionBuilt += value;
}
remove
{
this.ThrowWhenContainerIsLockedOrDisposed();
this.expressionBuilt -= value;
}
}
/// <summary>
/// Occurs directly after the creation of the <see cref="Expression" /> of a registered type is made,
/// but before any <see cref="RegisterInitializer">initializer</see> and lifestyle specific caching
/// has been applied, allowing the created <see cref="Expression" /> to be altered. Multiple delegates
/// may handle the same service type.
/// </summary>
/// <remarks>
/// <para>
/// The <b>ExpressionBuilding</b> event is called by the container every time an registered type is
/// getting compiled, allowing a developer to change the way the type is created. The delegate that
/// hooks to the <b>ExpressionBuilding</b> event, can change the
/// <see cref="ExpressionBuildingEventArgs.Expression" /> property on the
/// <see cref="ExpressionBuildingEventArgs"/>, which allows changing the way the type is constructed.
/// </para>
/// <para>
/// The exact <see cref="Expression"/> type supplied depends on the type of registration.
/// Registrations that explicitly supply the implementation type (such as
/// <see cref="Register{TService, TImplementation}()">Register<TService, TImplementation>()</see>)
/// will result in an <see cref="NewExpression"/>, while registrations that take a delegate (such as
/// <see cref="Register{TService}(Func{TService})">Register<TService>(Func<TService>)</see>)
/// will result in an <see cref="InvocationExpression"/>. Singletons that are passed in using their
/// value (<see cref="RegisterSingleton{TService}(TService)">RegisterSingleton<TService>(TService)</see>)
/// will result in an <see cref="ConstantExpression"/>. Note that other <b>ExpressionBuilding</b>
/// registrations might have changed the <see cref="ExpressionBuildingEventArgs.Expression" />
/// property and might have supplied an <see cref="Expression"/> of a different type. The order in
/// which these events are registered might be of importance to you.
/// </para>
/// <para>
/// <b>Thread-safety:</b> Please note that the container will not ensure that the hooked delegates
/// are executed only once per service type. While the calls to registered <b>ExpressionBuilding</b>
/// events for a given type are finite (and will in most cases happen just once), a container can
/// call the delegate multiple times and make parallel calls to the delegate. You must make sure that
/// the code can be called multiple times and is thread-safe.
/// </para>
/// </remarks>
/// <example>
/// The following example shows the usage of the <b>ExpressionBuilding</b> event:
/// <code lang="cs"><![CDATA[
/// public class MyInjectPropertyAttribute : Attribute { }
///
/// public static void Bootstrap()
/// {
/// var container = new Container();
///
/// container.ExpressionBuilding += (sender, e) =>
/// {
/// var expression = e.Expression as NewExpression;
///
/// if (expression != null)
/// {
/// var propertiesToInject =
/// from property in expression.Constructor.DeclaringType.GetProperties()
/// where property.GetCustomAttributes(typeof(MyInjectPropertyAttribute), true).Any()
/// let registration = container.GetRegistration(property.PropertyType, true)
/// select Tuple.Create(property, registration);
///
/// if (propertiesToInject.Any())
/// {
/// Func<object, Tuple<PropertyInfo, InstanceProducer>[], object> injectorDelegate =
/// (instance, dependencies) =>
/// {
/// foreach (var dependency in dependencies)
/// {
/// dependency.Item1.SetValue(instance, dependency.Item2.GetInstance(), null);
/// }
///
/// return instance;
/// };
///
/// e.Expression = Expression.Convert(
/// Expression.Invoke(
/// Expression.Constant(injectorDelegate),
/// e.Expression,
/// Expression.Constant(propertiesToInject.ToArray())),
/// expression.Constructor.DeclaringType);
/// }
/// }
/// };
/// }
/// ]]></code>
/// <para>
/// The example above registers a delegate that is raised every time the container compiles the
/// expression for an registered type. The delegate checks if the type contains properties that are
/// decorated with the supplied <b>MyInjectPropertyAttribute</b>. If decorated properties are found,
/// the given expression is replaced with an expression that injects decorated properties.
/// </para>
/// </example>
public event EventHandler<ExpressionBuildingEventArgs> ExpressionBuilding
{
add
{
this.ThrowWhenContainerIsLockedOrDisposed();
this.expressionBuilding += value;
}
remove
{
this.ThrowWhenContainerIsLockedOrDisposed();
this.expressionBuilding -= value;
}
}
// Allows getting notified when Verify() is called.
// This event is currently only used by RegisterCollection to make sure that as many registered types
// can be verified.
internal event Action Verifying = () => { };
/// <summary>
/// Registers that a new instance of <typeparamref name="TConcrete"/> will be returned every time it
/// is requested (transient).
/// </summary>
/// <remarks>
/// This method uses the container's
/// <see cref="ContainerOptions.LifestyleSelectionBehavior">LifestyleSelectionBehavior</see> to select
/// the exact lifestyle for the specified type. By default this will be
/// <see cref="Lifestyle.Transient">Transient</see>.
/// </remarks>
/// <typeparam name="TConcrete">The concrete type that will be registered.</typeparam>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <typeparamref name="TConcrete"/> has already been registered.
/// </exception>
/// <exception cref="ArgumentException">Thrown when the <typeparamref name="TConcrete"/> is a type
/// that can not be created by the container.</exception>
public void Register<TConcrete>() where TConcrete : class
{
this.Register<TConcrete, TConcrete>(this.SelectionBasedLifestyle, "TConcrete", "TConcrete");
}
/// <summary>
/// Registers that an instance of <typeparamref name="TConcrete"/> will be returned when it
/// is requested. The instance is cached according to the supplied <paramref name="lifestyle"/>.
/// </summary>
/// <typeparam name="TConcrete">The concrete type that will be registered.</typeparam>
/// <param name="lifestyle">The lifestyle that specifies how the returned instance will be cached.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <typeparamref name="TConcrete"/> has already been registered.
/// </exception>
/// <exception cref="ArgumentException">Thrown when the <typeparamref name="TConcrete"/> is a type
/// that can not be created by the container.</exception>
public void Register<TConcrete>(Lifestyle lifestyle) where TConcrete : class
{
this.Register<TConcrete, TConcrete>(lifestyle, "TConcrete", "TConcrete");
}
/// <summary>
/// Registers that a new instance of <typeparamref name="TImplementation"/> will be returned every time a
/// <typeparamref name="TService"/> is requested (transient).
/// </summary>
/// <remarks>
/// This method uses the container's
/// <see cref="ContainerOptions.LifestyleSelectionBehavior">LifestyleSelectionBehavior</see> to select
/// the exact lifestyle for the specified type. By default this will be
/// <see cref="Lifestyle.Transient">Transient</see>.
/// </remarks>
/// <typeparam name="TService">The interface or base type that can be used to retrieve the instances.</typeparam>
/// <typeparam name="TImplementation">The concrete type that will be registered.</typeparam>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <typeparamref name="TService"/> has already been registered.</exception>
/// <exception cref="ArgumentException">Thrown when the given <typeparamref name="TImplementation"/>
/// type is not a type that can be created by the container.
/// </exception>
public void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
this.Register<TService, TImplementation>(this.SelectionBasedLifestyle, "TService", "TImplementation");
}
/// <summary>
/// Registers that an instance of <typeparamref name="TImplementation"/> will be returned when an
/// instance of type <typeparamref name="TService"/> is requested. The instance is cached according to
/// the supplied <paramref name="lifestyle"/>.
/// </summary>
/// <typeparam name="TService">The interface or base type that can be used to retrieve the instances.</typeparam>
/// <typeparam name="TImplementation">The concrete type that will be registered.</typeparam>
/// <param name="lifestyle">The lifestyle that specifies how the returned instance will be cached.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <typeparamref name="TService"/> has already been registered.</exception>
/// <exception cref="ArgumentException">Thrown when the given <typeparamref name="TImplementation"/>
/// type is not a type that can be created by the container.
/// </exception>
public void Register<TService, TImplementation>(Lifestyle lifestyle)
where TImplementation : class, TService
where TService : class
{
this.Register<TService, TImplementation>(lifestyle, "TService", "TImplementation");
}
/// <summary>
/// Registers the specified delegate that allows returning transient instances of
/// <typeparamref name="TService"/>. The delegate is expected to always return a new instance on
/// each call.
/// </summary>
/// <remarks>
/// This method uses the container's
/// <see cref="ContainerOptions.LifestyleSelectionBehavior">LifestyleSelectionBehavior</see> to select
/// the exact lifestyle for the specified type. By default this will be
/// <see cref="Lifestyle.Transient">Transient</see>.
/// </remarks>
/// <typeparam name="TService">The interface or base type that can be used to retrieve instances.</typeparam>
/// <param name="instanceCreator">The delegate that allows building or creating new instances.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when the
/// <typeparamref name="TService"/> has already been registered.</exception>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="instanceCreator"/> is a null reference.</exception>
public void Register<TService>(Func<TService> instanceCreator) where TService : class
{
this.Register<TService>(instanceCreator, this.SelectionBasedLifestyle);
}
/// <summary>
/// Registers the specified delegate <paramref name="instanceCreator"/> that will produce instances of
/// type <typeparamref name="TService"/> and will be returned when an instance of type
/// <typeparamref name="TService"/> is requested. The delegate is expected to produce new instances on
/// each call. The instances are cached according to the supplied <paramref name="lifestyle"/>.
/// </summary>
/// <typeparam name="TService">The interface or base type that can be used to retrieve instances.</typeparam>
/// <param name="instanceCreator">The delegate that allows building or creating new instances.</param>
/// <param name="lifestyle">The lifestyle that specifies how the returned instance will be cached.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when the
/// <typeparamref name="TService"/> has already been registered.</exception>
/// <exception cref="ArgumentNullException">
/// Thrown when one of the supplied arguments is a null reference (Nothing in VB).</exception>
public void Register<TService>(Func<TService> instanceCreator, Lifestyle lifestyle)
where TService : class
{
Requires.IsNotNull(instanceCreator, nameof(instanceCreator));
Requires.IsNotNull(lifestyle, nameof(lifestyle));
Requires.IsNotAnAmbiguousType(typeof(TService), nameof(TService));
var registration = lifestyle.CreateRegistration<TService>(instanceCreator, this);
this.AddRegistration(typeof(TService), registration);
}
/// <summary>
/// Registers that a new instance of <paramref name="concreteType"/> will be returned every time it
/// is requested (transient).
/// </summary>
/// <remarks>
/// This method uses the container's
/// <see cref="ContainerOptions.LifestyleSelectionBehavior">LifestyleSelectionBehavior</see> to select
/// the exact lifestyle for the specified type. By default this will be
/// <see cref="Lifestyle.Transient">Transient</see>.
/// </remarks>
/// <param name="concreteType">The concrete type that will be registered.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="concreteType"/> is a null
/// references (Nothing in VB).</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="concreteType"/> represents an
/// open generic type or is a type that can not be created by the container.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <paramref name="concreteType"/> has already been registered.
/// </exception>
public void Register(Type concreteType)
{
this.Register(concreteType, concreteType, this.SelectionBasedLifestyle, nameof(concreteType), nameof(concreteType));
}
/// <summary>
/// Registers that a new instance of <paramref name="implementationType"/> will be returned every time a
/// <paramref name="serviceType"/> is requested. If <paramref name="serviceType"/> and
/// <paramref name="implementationType"/> represent the same type, the type is registered by itself.
/// Open and closed generic types are supported.
/// </summary>
/// <remarks>
/// This method uses the container's
/// <see cref="ContainerOptions.LifestyleSelectionBehavior">LifestyleSelectionBehavior</see> to select
/// the exact lifestyle for the specified type. By default this will be
/// <see cref="Lifestyle.Transient">Transient</see>.
/// </remarks>
/// <param name="serviceType">The base type or interface to register. This can be an open-generic type.</param>
/// <param name="implementationType">The actual type that will be returned when requested.
/// This can be an open-generic type.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="serviceType"/> or
/// <paramref name="implementationType"/> are null references (Nothing in VB).</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="implementationType"/> is
/// no sub type from <paramref name="serviceType"/> (or the same type).
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <paramref name="serviceType"/> has already been registered.
/// </exception>
public void Register(Type serviceType, Type implementationType)
{
this.Register(serviceType, implementationType, this.SelectionBasedLifestyle,
nameof(serviceType), nameof(implementationType));
}
/// <summary>
/// Registers that an instance of type <paramref name="implementationType"/> will be returned when an
/// instance of type <paramref name="serviceType"/> is requested. The instance is cached according to
/// the supplied <paramref name="lifestyle"/>. Open and closed generic types are supported.
/// </summary>
/// <param name="serviceType">The interface or base type that can be used to retrieve the instances.
/// This can be an open-generic type.</param>
/// <param name="implementationType">The concrete type that will be registered.
/// This can be an open-generic type.</param>
/// <param name="lifestyle">The lifestyle that specifies how the returned instance will be cached.</param>
/// <exception cref="ArgumentNullException">Thrown when one of the supplied arguments is a null
/// reference (Nothing in VB).</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when the
/// <paramref name="serviceType"/> has already been registered.</exception>
/// <exception cref="ArgumentException">Thrown when the given <paramref name="implementationType"/>
/// type is not a type that can be created by the container, when either <paramref name="serviceType"/>
/// or <paramref name="implementationType"/> are open generic types, or when
/// <paramref name="serviceType"/> is not assignable from the <paramref name="implementationType"/>.
/// </exception>
/// <exception cref="ArgumentNullException">Thrown when one of the supplied arguments is a null
/// reference (Nothing in VB).</exception>
public void Register(Type serviceType, Type implementationType, Lifestyle lifestyle)
{
this.Register(serviceType, implementationType, lifestyle, nameof(serviceType), nameof(implementationType));
}
/// <summary>
/// Registers the specified delegate that allows returning instances of <paramref name="serviceType"/>.
/// </summary>
/// <remarks>
/// This method uses the container's
/// <see cref="ContainerOptions.LifestyleSelectionBehavior">LifestyleSelectionBehavior</see> to select
/// the exact lifestyle for the specified type. By default this will be
/// <see cref="Lifestyle.Transient">Transient</see>.
/// </remarks>
/// <param name="serviceType">The base type or interface to register.</param>
/// <param name="instanceCreator">The delegate that will be used for creating new instances.</param>
/// <exception cref="ArgumentNullException">Thrown when either <paramref name="serviceType"/> or
/// <paramref name="instanceCreator"/> are null references (Nothing in VB).</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="serviceType"/> represents an
/// open generic type.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <paramref name="serviceType"/> has already been registered.
/// </exception>
public void Register(Type serviceType, Func<object> instanceCreator)
{
this.Register(serviceType, instanceCreator, this.SelectionBasedLifestyle);
}
/// <summary>
/// Registers the specified delegate <paramref name="instanceCreator"/> that will produce instances of
/// type <paramref name="serviceType"/> and will be returned when an instance of type
/// <paramref name="serviceType"/> is requested. The delegate is expected to produce new instances on
/// each call. The instances are cached according to the supplied <paramref name="lifestyle"/>.
/// </summary>
/// <param name="serviceType">The interface or base type that can be used to retrieve instances.</param>
/// <param name="instanceCreator">The delegate that allows building or creating new instances.</param>
/// <param name="lifestyle">The lifestyle that specifies how the returned instance will be cached.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when the
/// <paramref name="serviceType"/> has already been registered.</exception>
/// <exception cref="ArgumentNullException">
/// Thrown when one of the supplied arguments is a null reference (Nothing in VB).</exception>
public void Register(Type serviceType, Func<object> instanceCreator, Lifestyle lifestyle)
{
Requires.IsNotNull(serviceType, nameof(serviceType));
Requires.IsNotNull(instanceCreator, nameof(instanceCreator));
Requires.IsNotNull(lifestyle, nameof(lifestyle));
Requires.IsReferenceType(serviceType, nameof(serviceType));
Requires.IsNotOpenGenericType(serviceType, nameof(serviceType));
Requires.IsNotAnAmbiguousType(serviceType, nameof(serviceType));
var registration = lifestyle.CreateRegistration(serviceType, instanceCreator, this);
this.AddRegistration(serviceType, registration);
}
/// <summary>
/// Registers a single instance that will be returned when an instance of type
/// <typeparamref name="TService"/> is requested. This <paramref name="instance"/> must be thread-safe
/// when working in a multi-threaded environment.
/// <b>NOTE:</b> Do note that instances supplied by this method <b>NEVER</b> get disposed by the
/// container, since the instance is assumed to outlive this container instance. If disposing is
/// required, use the overload that accepts a <see cref="Func{T}"/> delegate.
/// </summary>
/// <typeparam name="TService">The interface or base type that can be used to retrieve the instance.</typeparam>
/// <param name="instance">The instance to register.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when the
/// <typeparamref name="TService"/> has already been registered.</exception>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="instance"/> is a null reference.
/// </exception>
public void RegisterSingleton<TService>(TService instance) where TService : class
{
Requires.IsNotNull(instance, nameof(instance));
Requires.IsNotAnAmbiguousType(typeof(TService), nameof(TService));
var registration = SingletonLifestyle.CreateSingleInstanceRegistration(typeof(TService), instance, this,
instance.GetType());
this.AddRegistration(typeof(TService), registration);
}
/// <summary>
/// Registers a single instance that will be returned when an instance of type
/// <paramref name="serviceType"/> is requested. This <paramref name="instance"/> must be thread-safe
/// when working in a multi-threaded environment.
/// </summary>
/// <param name="serviceType">The base type or interface to register.</param>
/// <param name="instance">The instance to register.</param>
/// <exception cref="ArgumentNullException">Thrown when either <paramref name="serviceType"/> or
/// <paramref name="instance"/> are null references (Nothing in VB).</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="instance"/> is
/// no sub type from <paramref name="serviceType"/>.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <paramref name="serviceType"/> has already been registered.
/// </exception>
public void RegisterSingleton(Type serviceType, object instance)
{
Requires.IsNotNull(serviceType, nameof(serviceType));
Requires.IsNotNull(instance, nameof(instance));
Requires.ServiceIsAssignableFromImplementation(serviceType, instance.GetType(), nameof(serviceType));
Requires.IsNotAnAmbiguousType(serviceType, nameof(serviceType));
var registration = SingletonLifestyle.CreateSingleInstanceRegistration(serviceType, instance, this);
this.AddRegistration(serviceType, registration);
}
/// <summary>
/// Registers a single concrete instance that will be constructed using constructor injection and will
/// be returned when this instance is requested by type <typeparamref name="TConcrete"/>.
/// This <typeparamref name="TConcrete"/> must be thread-safe when working in a multi-threaded
/// environment.
/// If <typeparamref name="TConcrete"/> implements <see cref="IDisposable"/>, a created instance will
/// get disposed when <see cref="Container.Dispose()">Container.Dispose</see> gets called.
/// </summary>
/// <typeparam name="TConcrete">The concrete type that will be registered.</typeparam>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when
/// <typeparamref name="TConcrete"/> has already been registered.
/// </exception>
/// <exception cref="ArgumentException">Thrown when the <typeparamref name="TConcrete"/> is a type
/// that can not be created by the container.</exception>
public void RegisterSingleton<TConcrete>() where TConcrete : class
{
this.Register<TConcrete, TConcrete>(Lifestyle.Singleton, nameof(TConcrete), nameof(TConcrete));
}
/// <summary>
/// Registers that the same a single instance of type <typeparamref name="TImplementation"/> will be
/// returned every time an <typeparamref name="TService"/> type is requested. If
/// <typeparamref name="TService"/> and <typeparamref name="TImplementation"/> represent the same
/// type, the type is registered by itself. <typeparamref name="TImplementation"/> must be thread-safe
/// when working in a multi-threaded environment.
/// If <typeparamref name="TImplementation"/> implements <see cref="IDisposable"/>, a created instance will
/// get disposed when <see cref="Container.Dispose()">Container.Dispose</see> gets called.
/// </summary>
/// <typeparam name="TService">
/// The interface or base type that can be used to retrieve the instances.
/// </typeparam>
/// <typeparam name="TImplementation">The concrete type that will be registered.</typeparam>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when the
/// <typeparamref name="TService"/> has already been registered.</exception>
/// <exception cref="ArgumentException">Thrown when the given <typeparamref name="TImplementation"/>
/// type is not a type that can be created by the container.
/// </exception>
public void RegisterSingleton<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
this.Register<TService, TImplementation>(Lifestyle.Singleton, nameof(TService), nameof(TImplementation));
}
/// <summary>
/// Registers the specified delegate that allows constructing a single instance of
/// <typeparamref name="TService"/>. This delegate will be called at most once during the lifetime of
/// the application. The returned instance must be thread-safe when working in a multi-threaded
/// environment.
/// If the instance returned from <paramref name="instanceCreator"/> implements <see cref="IDisposable"/>,
/// the created instance will get disposed when <see cref="Container.Dispose()">Container.Dispose</see>
/// gets called.
/// </summary>
/// <typeparam name="TService">The interface or base type that can be used to retrieve instances.</typeparam>
/// <param name="instanceCreator">The delegate that allows building or creating this single
/// instance.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when a
/// <paramref name="instanceCreator"/> for <typeparamref name="TService"/> has already been registered.
/// </exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="instanceCreator"/> is a
/// null reference.</exception>
public void RegisterSingleton<TService>(Func<TService> instanceCreator) where TService : class
{
Requires.IsNotNull(instanceCreator, nameof(instanceCreator));
Requires.IsNotAnAmbiguousType(typeof(TService), nameof(TService));
this.Register<TService>(instanceCreator, Lifestyle.Singleton);
}
/// <summary>
/// Registers that the same instance of type <paramref name="implementationType"/> will be returned every
/// time an instance of type <paramref name="serviceType"/> type is requested. If
/// <paramref name="serviceType"/> and <paramref name="implementationType"/> represent the same type, the
/// type is registered by itself. <paramref name="implementationType"/> must be thread-safe when working
/// in a multi-threaded environment. Open and closed generic types are supported.
/// </summary>
/// <param name="serviceType">The base type or interface to register.
/// This can be an open-generic type.</param>
/// <param name="implementationType">The actual type that will be returned when requested.
/// This can be an open-generic type.</param>
/// <exception cref="ArgumentNullException">Thrown when either <paramref name="serviceType"/> or
/// <paramref name="implementationType"/> are null references (Nothing in VB).</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="implementationType"/> is
/// no sub type from <paramref name="serviceType"/>, or when one of them represents an open generic
/// type.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <paramref name="serviceType"/> has already been registered.
/// </exception>
public void RegisterSingleton(Type serviceType, Type implementationType)
{
this.Register(serviceType, implementationType, Lifestyle.Singleton, nameof(serviceType),
nameof(implementationType));
}
/// <summary>
/// Registers the specified delegate that allows constructing a single <paramref name="serviceType"/>
/// instance. The container will call this delegate at most once during the lifetime of the application.
/// </summary>
/// <param name="serviceType">The base type or interface to register.</param>
/// <param name="instanceCreator">The delegate that will be used for creating that single instance.</param>
/// <exception cref="ArgumentException">Thrown when <paramref name="serviceType"/> represents an open
/// generic type.</exception>
/// <exception cref="ArgumentNullException">Thrown when either <paramref name="serviceType"/> or
/// <paramref name="instanceCreator"/> are null references (Nothing in
/// VB).</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered, or when an
/// the <paramref name="serviceType"/> has already been registered.
/// </exception>
public void RegisterSingleton(Type serviceType, Func<object> instanceCreator)
{
this.Register(serviceType, instanceCreator, Lifestyle.Singleton);
}
/// <summary>
/// Registers an <see cref="Action{T}"/> delegate that runs after the creation of instances that
/// implement or derive from the given <typeparamref name="TService"/>. Please note that only instances
/// that are created by the container (using constructor injection) can be initialized this way.
/// </summary>
/// <typeparam name="TService">The type for which the initializer will be registered.</typeparam>
/// <param name="instanceInitializer">The delegate that will be called after the instance has been
/// constructed and before it is returned.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="instanceInitializer"/> is a null reference.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered.</exception>
/// <remarks>
/// <para>
/// Multiple <paramref name="instanceInitializer"/> delegates can be registered per
/// <typeparamref name="TService"/> and multiple initializers can be applied on a created instance,
/// before it is returned. For instance, when registering a <paramref name="instanceInitializer"/>
/// for type <see cref="System.Object"/>, the delegate will be called for every instance created by
/// the container, which can be nice for debugging purposes.
/// </para>
/// <para>
/// Note: Initializers are guaranteed to be executed in the order they are registered.
/// </para>
/// <para>
/// The following example shows the usage of the
/// <see cref="RegisterInitializer{TService}(Action{TService})">RegisterInitializer</see> method:
/// </para>
/// <code lang="cs"><![CDATA[
/// public interface ITimeProvider { DateTime Now { get; } }
/// public interface ICommand { bool SendAsync { get; set; } }
///
/// public abstract class CommandBase : ICommand
/// {
/// ITimeProvider Clock { get; set; }
///
/// public bool SendAsync { get; set; }
/// }
///
/// public class ConcreteCommand : CommandBase { }
///
/// [TestMethod]
/// public static void TestRegisterInitializer()
/// {
/// // Arrange
/// var container = new Container();
///
/// container.Register<ICommand, ConcreteCommand>();
///
/// // Configuring property injection for types that implement ICommand:
/// container.RegisterInitializer<ICommand>(command =>
/// {
/// command.SendAsync = true;
/// });
///
/// // Configuring property injection for types that implement CommandBase:
/// container.RegisterInitializer<CommandBase>(command =>
/// {
/// command.Clock = container.GetInstance<ITimeProvider>();
/// });
///
/// // Act
/// var command = (ConcreteCommand)container.GetInstance<ICommand>();
///
/// // Assert
/// // Because ConcreteCommand implements both ICommand and CommandBase,
/// // both the initializers will have been executed.
/// Assert.IsTrue(command.SendAsync);
/// Assert.IsNotNull(command.Clock);
/// }
/// ]]></code>
/// <para>
/// The container does not use the type information of the requested service type, but it uses the
/// type information of the actual implementation to find all initialized that apply for that
/// type. This makes it possible to have multiple initializers to be applied on a single returned
/// instance while keeping performance high.
/// </para>
/// <para>
/// Registered initializers will only be applied to instances that are created by the container self
/// (using constructor injection). Types that are newed up manually by supplying a
/// <see cref="Func{T}"/> delegate to the container (using the
/// <see cref="Register{TService}(Func{TService})"/> method) or registered as single instance
/// (using <see cref="RegisterSingleton{TService}(TService)"/>) will not trigger initialization.
/// When initialization of these instances is needed, this must be done manually, as can be seen in
/// the following example:
/// <code lang="cs"><![CDATA[
/// [TestMethod]
/// public static void TestRegisterInitializer()
/// {
/// // Arrange
/// int initializerCallCount = 0;
///
/// var container = new Container();
///
/// // Define a initializer for ICommand
/// Action<ICommand> commandInitializer = command =>
/// {
/// initializerCallCount++;
/// });
///
/// // Configuring that initializer.
/// container.RegisterInitializer<ICommand>(commandInitializer);
///
/// container.Register<ICommand>(() =>
/// {
/// // Create a ConcreteCommand manually: will not be initialized.
/// var command = new ConcreteCommand("Data Source=.;Initial Catalog=db;");
///
/// // Run the initializer manually.
/// commandInitializer(command);
///
/// return command;
/// });
///
/// // Act
/// var command = container.GetInstance<ICommand>();
///
/// // Assert
/// // The initializer will only be called once.
/// Assert.AreEqual(1, initializerCallCount);
/// }
/// ]]></code>
/// The previous example shows how a manually created instance can still be initialized. Try to
/// prevent creating types manually, by changing the design of those classes. If possible, create a
/// single public constructor that only contains dependencies that can be resolved.
/// </para>
/// </remarks>
public void RegisterInitializer<TService>(Action<TService> instanceInitializer) where TService : class
{
Requires.IsNotNull(instanceInitializer, nameof(instanceInitializer));
this.ThrowWhenContainerIsLockedOrDisposed();
this.instanceInitializers.Add(TypedInstanceInitializer.Create(instanceInitializer));
}
/// <summary>
/// Registers an <see cref="Action{InstanceInitializationData}"/> delegate that runs after the
/// creation of instances for which the supplied <paramref name="predicate"/> returns true. Please
/// note that only instances that are created by the container can be initialized this way.
/// </summary>
/// <param name="instanceInitializer">The delegate that will be called after the instance has been
/// constructed and before it is returned.</param>
/// <param name="predicate">The predicate that will be used to check whether the given delegate must
/// be applied to a registration or not. The given predicate will be called once for each registration
/// in the container.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when either the <paramref name="instanceInitializer"/> or <paramref name="predicate"/> are
/// null references.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when this container instance is locked and can not be altered.</exception>
/// <remarks>
/// <para>
/// Note: Initializers are guaranteed to be executed in the order they are registered.
/// </para>
/// <para>
/// Note: The <paramref name="predicate"/> is <b>not</b> guaranteed to be called once per registration;
/// when a registration's instance is requested for the first time simultaneously over multiple thread,
/// the predicate might be called multiple times. The caller of this method is responsible of supplying
/// a predicate that is thread-safe.
/// </para>
/// </remarks>
public void RegisterInitializer(Action<InstanceInitializationData> instanceInitializer,
Predicate<InitializerContext> predicate)
{