PageRenderTime 208ms CodeModel.GetById 202ms app.highlight 3ms RepoModel.GetById 2ms app.codeStats 0ms

/src/LinFu.IoC/Interceptors/InvocationInfoInterceptor.cs

http://github.com/philiplaureano/LinFu
C# | 63 lines | 36 code | 8 blank | 19 comment | 4 complexity | 35da634cd8e96c41bf7d8b3ac718ba50 MD5 | raw file
 1using System;
 2using System.Reflection;
 3using LinFu.AOP.Interfaces;
 4using LinFu.IoC.Configuration.Interfaces;
 5
 6namespace LinFu.IoC.Interceptors
 7{
 8    /// <summary>
 9    ///     An interceptor that intercepts <see cref="IInvocationInfo" /> instances
10    ///     and replaces the original target instance with a surrogate instance.
11    /// </summary>
12    internal class InvocationInfoInterceptor : BaseInterceptor
13    {
14        private static readonly MethodInfo _targetMethod;
15        private readonly Func<object> _getActualTarget;
16        private readonly IInvocationInfo _realInfo;
17
18        static InvocationInfoInterceptor()
19        {
20            var targetProperty = typeof(IInvocationInfo).GetProperty("Target");
21            _targetMethod = targetProperty.GetGetMethod();
22        }
23
24        /// <summary>
25        ///     Initializes the class with a functor that can provide the actual target instance.
26        /// </summary>
27        /// <param name="getActualTarget">
28        ///     The <see cref="Func{TResult}" /> that will provide the target instance that will be used
29        ///     for the method invocation.
30        /// </param>
31        /// <param name="methodInvoke">The method invoker.</param>
32        /// <param name="realInfo">The <see cref="IInvocationInfo" /> instance that describes the current execution context.</param>
33        internal InvocationInfoInterceptor(IInvocationInfo realInfo, Func<object> getActualTarget,
34            IMethodInvoke<MethodInfo> methodInvoke) : base(methodInvoke)
35        {
36            _getActualTarget = getActualTarget;
37            _realInfo = realInfo;
38        }
39
40        public override object Intercept(IInvocationInfo info)
41        {
42            var targetMethod = info.TargetMethod;
43
44            // Intercept calls made only to the IInvocationInfo interface
45            if (targetMethod.DeclaringType != typeof(IInvocationInfo) || targetMethod.Name != "get_Target")
46                return base.Intercept(info);
47
48            var target = _getActualTarget();
49
50            // Replace the proxy with the actual target           
51            return target;
52        }
53
54        /// <summary>
55        ///     Gets the target object instance.
56        /// </summary>
57        /// <param name="info">The <see cref="IInvocationInfo" /> instance that describes the current execution context.</param>
58        protected override object GetTarget(IInvocationInfo info)
59        {
60            return _realInfo;
61        }
62    }
63}