/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

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