PageRenderTime 27ms CodeModel.GetById 22ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.IoC/Configuration/Injectors/AutoFieldInjector.cs

http://github.com/philiplaureano/LinFu
C# | 42 lines | 19 code | 3 blank | 20 comment | 4 complexity | d77e53aa4be28e57544221bde4eaae7b MD5 | raw file
 1using System.Reflection;
 2using LinFu.IoC.Configuration.Interfaces;
 3using LinFu.IoC.Interfaces;
 4
 5namespace LinFu.IoC.Configuration
 6{
 7    /// <summary>
 8    ///     A class that automatically injects fields using values
 9    ///     provided by an <see cref="IServiceContainer" /> instance.
10    /// </summary>
11    public class AutoFieldInjector : AutoMemberInjector<FieldInfo>
12    {
13        /// <summary>
14        ///     Injects a field with values from a given container.
15        /// </summary>
16        /// <param name="target">The target object.</param>
17        /// <param name="member">The <see cref="FieldInfo" /> instance that will store the service instance.</param>
18        /// <param name="argumentResolver">
19        ///     The <see cref="IArgumentResolver" /> that will determine which values will be assigned
20        ///     to the target member.
21        /// </param>
22        /// <param name="additionalArguments">
23        ///     The additional arguments that were passed to the <see cref="IServiceRequestResult" />
24        ///     during the instantiation process. Note: This parameter will be ignored by this override.
25        /// </param>
26        /// <param name="container">The container that will provide the service instances.</param>
27        protected override void Inject(object target, FieldInfo member, IArgumentResolver argumentResolver,
28            IServiceContainer container, object[] additionalArguments)
29        {
30            // Get the field value from the container
31            var fieldType = new NamedType(member.FieldType);
32            var fieldValues = argumentResolver.ResolveFrom(new[] {fieldType}, container);
33
34            if (fieldValues == null || fieldValues.Length == 0)
35                return;
36
37            // Cast the field value to the target type
38            var value = fieldValues[0];
39            member.SetValue(target, value);
40        }
41    }
42}