PageRenderTime 6ms CodeModel.GetById 1ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.IoC/Configuration/Injectors/CustomFactoryInjector.cs

http://github.com/philiplaureano/LinFu
C# | 60 lines | 28 code | 9 blank | 23 comment | 9 complexity | a1aed767456686f6011368e537c69113 MD5 | raw file
 1using System;
 2using LinFu.IoC.Interfaces;
 3
 4namespace LinFu.IoC.Configuration.Injectors
 5{
 6    /// <summary>
 7    ///     A class that injects unnamed custom <see cref="IFactory" /> instances into a given
 8    ///     service container.
 9    /// </summary>
10    public class CustomFactoryInjector : IPreProcessor
11    {
12        private readonly IFactory _factory;
13        private readonly Type _serviceType;
14
15        /// <summary>
16        ///     Initializes the class with the given service type and factory.
17        /// </summary>
18        /// <param name="serviceType">The service type that will be created by the factory.</param>
19        /// <param name="factory">The <see cref="IFactory" /> instance that will be used to create the service instance.</param>
20        public CustomFactoryInjector(Type serviceType, IFactory factory)
21        {
22            _serviceType = serviceType;
23            _factory = factory;
24        }
25
26
27        /// <summary>
28        ///     Injects the given factory into the target container.
29        /// </summary>
30        /// <param name="request">
31        ///     The <see cref="IServiceRequest" /> instance that describes the service that is currently being
32        ///     requested.
33        /// </param>
34        public void Preprocess(IServiceRequest request)
35        {
36            // Inject the custom factory if no other
37            // replacement exists
38            if (request.ActualFactory != null)
39                return;
40
41            var serviceType = request.ServiceType;
42
43            // Skip any service requests for types that are generic type definitions
44            if (serviceType.IsGenericTypeDefinition)
45                return;
46
47            // If the current service type is a generic type,
48            // its type definition must match the given service type
49            if (serviceType.IsGenericType && serviceType.GetGenericTypeDefinition() != _serviceType)
50                return;
51
52            // The service types must match
53            if (!serviceType.IsGenericType && serviceType != _serviceType)
54                return;
55
56            // Inject the custom factory itself            
57            request.ActualFactory = _factory;
58        }
59    }
60}