PageRenderTime 167ms CodeModel.GetById 80ms app.highlight 10ms RepoModel.GetById 71ms app.codeStats 0ms

/src/LinFu.IoC/Interceptors/ProxyInjector.cs

http://github.com/philiplaureano/LinFu
C# | 56 lines | 30 code | 8 blank | 18 comment | 5 complexity | 34a70ab52eadb9b321f7c6a4bbdccc7d MD5 | raw file
 1using System;
 2using LinFu.IoC.Interfaces;
 3using LinFu.Proxy.Interfaces;
 4
 5namespace LinFu.IoC.Interceptors
 6{
 7    /// <summary>
 8    ///     Represents a class that automatically injects a proxy instance
 9    ///     instead of an actual service instance.
10    /// </summary>
11    public class ProxyInjector : IPostProcessor
12    {
13        private readonly Func<IServiceRequestResult, object> _createProxy;
14        private readonly Func<IServiceRequestResult, bool> _filterPredicate;
15
16        /// <summary>
17        ///     Initializes the class with the <paramref name="filterPredicate" />
18        ///     and the <paramref name="createProxy" /> factory method.
19        /// </summary>
20        /// <param name="filterPredicate">The predicate that will determine which service requests will be proxied.</param>
21        /// <param name="createProxy">The factory method that will generate the proxy instance itself.</param>
22        public ProxyInjector(Func<IServiceRequestResult, bool> filterPredicate,
23            Func<IServiceRequestResult, object> createProxy)
24        {
25            _filterPredicate = filterPredicate;
26            _createProxy = createProxy;
27        }
28
29
30        /// <summary>
31        ///     A method that injects service proxies in place of the actual <see cref="IServiceRequestResult.ActualResult" />.
32        /// </summary>
33        /// <param name="result">The <see cref="IServiceRequestResult" /> instance that describes the service request.</param>
34        public void PostProcess(IServiceRequestResult result)
35        {
36            if (!_filterPredicate(result))
37                return;
38
39            var container = result.Container;
40            var hasProxyFactory = container.Contains(typeof(IProxyFactory));
41
42            // Inject proxies only if a
43            // proxy factory instance is available
44            if (!hasProxyFactory)
45                return;
46
47            // Sealed types cannot be intercepted
48            var serviceType = result.ServiceType;
49            if (result.ActualResult != null && serviceType.IsSealed)
50                return;
51
52            // Replace the actual result with the proxy itself
53            result.ActualResult = _createProxy(result);
54        }
55    }
56}