PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 3ms RepoModel.GetById 37ms app.codeStats 0ms

/src/LinFu.IoC/Configuration/DefaultActivator.cs

http://github.com/philiplaureano/LinFu
C# | 60 lines | 32 code | 11 blank | 17 comment | 0 complexity | f33070c43014b818df607c60e41fdf55 MD5 | raw file
 1using System;
 2using System.Reflection;
 3using LinFu.AOP.Interfaces;
 4using LinFu.IoC.Configuration.Interfaces;
 5using LinFu.IoC.Interfaces;
 6
 7namespace LinFu.IoC.Configuration
 8{
 9    /// <summary>
10    ///     Represents a class that can instantiate object instances.
11    /// </summary>
12    public class DefaultActivator : IActivator<IContainerActivationContext>, IInitialize
13    {
14        private IConstructorArgumentResolver _argumentResolver;
15        private IMethodInvoke<ConstructorInfo> _constructorInvoke;
16        private IMemberResolver<ConstructorInfo> _resolver;
17
18
19        /// <summary>
20        ///     Creates an object instance.
21        /// </summary>
22        /// <returns>A valid object instance.</returns>
23        public object CreateInstance(IContainerActivationContext context)
24        {
25            var container = context.Container;
26            var additionalArguments = context.AdditionalArguments;
27            var concreteType = context.TargetType;
28
29            // Add the required services if necessary
30            container.AddDefaultServices();
31
32            var finderContext = new MethodFinderContext(new Type[0], additionalArguments, null);
33
34            // Determine which constructor
35            // contains the most resolvable
36            // parameters            
37            var constructor = _resolver.ResolveFrom(concreteType, container, finderContext);
38
39            // TODO: Allow users to insert their own custom constructor resolution routines here
40            var arguments = _argumentResolver.GetConstructorArguments(constructor, container, additionalArguments);
41
42            // Instantiate the object
43            var result = _constructorInvoke.Invoke(null, constructor, arguments);
44
45            return result;
46        }
47
48
49        /// <summary>
50        ///     Initializes the class with the default services.
51        /// </summary>
52        /// <param name="container">The target service container.</param>
53        public void Initialize(IServiceContainer container)
54        {
55            _resolver = container.GetService<IMemberResolver<ConstructorInfo>>();
56            _constructorInvoke = container.GetService<IMethodInvoke<ConstructorInfo>>();
57            _argumentResolver = container.GetService<IConstructorArgumentResolver>();
58        }
59    }
60}