PageRenderTime 102ms CodeModel.GetById 41ms app.highlight 22ms RepoModel.GetById 38ms app.codeStats 0ms

/src/LinFu.IoC/Factories/DelegateFactory.cs

http://github.com/philiplaureano/LinFu
C# | 58 lines | 36 code | 8 blank | 14 comment | 4 complexity | a368d553114cfeb4706f636e56c25114 MD5 | raw file
 1using System;
 2using System.Linq;
 3using System.Reflection;
 4using LinFu.IoC.Interfaces;
 5
 6namespace LinFu.IoC.Factories
 7{
 8    /// <summary>
 9    ///     Represents a class that uses a <see cref="MulticastDelegate" />
10    ///     to instantiate a service instance.
11    /// </summary>
12    public class DelegateFactory : IFactory
13    {
14        private readonly MulticastDelegate _targetDelegate;
15
16        /// <summary>
17        ///     Initializes the class with the given <paramref name="targetDelegate" />
18        /// </summary>
19        /// <param name="targetDelegate">The delegate that will be used to instantiate the factory.</param>
20        public DelegateFactory(MulticastDelegate targetDelegate)
21        {
22            if (targetDelegate.Method.ReturnType == typeof(void))
23                throw new ArgumentException("The factory delegate must have a return type.");
24
25            _targetDelegate = targetDelegate;
26        }
27
28
29        /// <summary>
30        ///     Instantiates the service type using the given delegate.
31        /// </summary>
32        /// <param name="request">The <see cref="IFactoryRequest" /> that describes the service that needs to be created.</param>
33        /// <returns>The service instance.</returns>
34        public object CreateInstance(IFactoryRequest request)
35        {
36            object result = null;
37            try
38            {
39                var target = _targetDelegate.Target;
40                var method = _targetDelegate.Method;
41                var argCount = request.Arguments.Length;
42                var methodArgCount = method.GetParameters().Count();
43
44                if (argCount != methodArgCount)
45                    throw new ArgumentException("Parameter Count Mismatch");
46
47                result = _targetDelegate.DynamicInvoke(request.Arguments);
48            }
49            catch (TargetInvocationException ex)
50            {
51                // Unroll the exception
52                throw ex.InnerException;
53            }
54
55            return result;
56        }
57    }
58}