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

/src/LinFu.IoC/Interceptors/LazyInterceptor.cs

http://github.com/philiplaureano/LinFu
C# | 63 lines | 35 code | 6 blank | 22 comment | 0 complexity | e1048807682a34dda184fcbf5e6ead2a MD5 | raw file
 1using System;
 2using System.Reflection;
 3using LinFu.AOP.Interfaces;
 4
 5namespace LinFu.IoC.Interceptors
 6{
 7    /// <summary>
 8    ///     An interceptor class that instantiates a target type only when
 9    ///     the methods for that target are invoked.
10    /// </summary>
11    /// <typeparam name="T">The type of object to intercept.</typeparam>
12    public class LazyInterceptor<T> : BaseInterceptor
13        where T : class
14    {
15        private readonly Func<T> _getInstance;
16
17        /// <summary>
18        ///     Initializes the class with the <paramref name="getInstance" />
19        ///     factory method.
20        /// </summary>
21        /// <param name="getInstance">The functor that will be used to create the actual object instance.</param>
22        public LazyInterceptor(Func<T> getInstance)
23        {
24            _getInstance = getInstance;
25        }
26
27        /// <summary>
28        ///     A method that uses the given factory method to provide a target
29        ///     for the method currently being invoked.
30        /// </summary>
31        /// <param name="info">The <see cref="IInvocationInfo" /> object that describes the current invocation context.</param>
32        /// <returns>The target itself.</returns>
33        protected override object GetTarget(IInvocationInfo info)
34        {
35            return _getInstance();
36        }
37
38        /// <summary>
39        ///     Intercepts the method and initializes the target instance before the
40        ///     actual object is invoked.
41        /// </summary>
42        /// <param name="info">The <see cref="IInvocationInfo" /> that describes the execution context.</param>
43        /// <returns>The return value of the target method.</returns>
44        public override object Intercept(IInvocationInfo info)
45        {
46            var target = _getInstance();
47            var arguments = info.Arguments;
48            var method = info.TargetMethod;
49
50            object result = null;
51            try
52            {
53                result = method.Invoke(target, arguments);
54            }
55            catch (TargetInvocationException ex)
56            {
57                throw ex.InnerException;
58            }
59
60            return result;
61        }
62    }
63}