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

http://github.com/philiplaureano/LinFu · C# · 47 lines · 23 code · 4 blank · 20 comment · 4 complexity · 43dca02897d52880610b6bb7e4b10f5d MD5 · raw file

  1. using System.Linq;
  2. using System.Reflection;
  3. using LinFu.IoC.Configuration.Interfaces;
  4. using LinFu.IoC.Interfaces;
  5. namespace LinFu.IoC.Configuration
  6. {
  7. /// <summary>
  8. /// A class that automatically injects property dependencies into
  9. /// service instances.
  10. /// </summary>
  11. public class AutoPropertyInjector : AutoMemberInjector<PropertyInfo>
  12. {
  13. /// <summary>
  14. /// Injects services from the <paramref name="container" /> into the target <see cref="PropertyInfo" /> instance.
  15. /// </summary>
  16. /// <param name="target">The target object.</param>
  17. /// <param name="property">The <see cref="PropertyInfo" /> instance that will store the service instance.</param>
  18. /// <param name="resolver">
  19. /// The <see cref="IArgumentResolver" /> that will determine which arguments will be assigned to the
  20. /// 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.
  25. /// </param>
  26. /// <param name="container">The container that will provide the service instances.</param>
  27. protected override void Inject(object target, PropertyInfo property,
  28. IArgumentResolver resolver, IServiceContainer container,
  29. object[] additionalArguments)
  30. {
  31. var setter = container.GetService<IPropertySetter>();
  32. if (setter == null)
  33. return;
  34. // Determine the property value
  35. var results = resolver.ResolveFrom(new[] {new NamedType(property)}, container);
  36. var propertyValue = results.FirstOrDefault();
  37. if (propertyValue == null)
  38. return;
  39. // Call the setter against the target property
  40. setter.Set(target, property, propertyValue);
  41. }
  42. }
  43. }