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

http://github.com/philiplaureano/LinFu · C# · 60 lines · 28 code · 9 blank · 23 comment · 9 complexity · a1aed767456686f6011368e537c69113 MD5 · raw file

  1. using System;
  2. using LinFu.IoC.Interfaces;
  3. namespace LinFu.IoC.Configuration.Injectors
  4. {
  5. /// <summary>
  6. /// A class that injects unnamed custom <see cref="IFactory" /> instances into a given
  7. /// service container.
  8. /// </summary>
  9. public class CustomFactoryInjector : IPreProcessor
  10. {
  11. private readonly IFactory _factory;
  12. private readonly Type _serviceType;
  13. /// <summary>
  14. /// Initializes the class with the given service type and factory.
  15. /// </summary>
  16. /// <param name="serviceType">The service type that will be created by the factory.</param>
  17. /// <param name="factory">The <see cref="IFactory" /> instance that will be used to create the service instance.</param>
  18. public CustomFactoryInjector(Type serviceType, IFactory factory)
  19. {
  20. _serviceType = serviceType;
  21. _factory = factory;
  22. }
  23. /// <summary>
  24. /// Injects the given factory into the target container.
  25. /// </summary>
  26. /// <param name="request">
  27. /// The <see cref="IServiceRequest" /> instance that describes the service that is currently being
  28. /// requested.
  29. /// </param>
  30. public void Preprocess(IServiceRequest request)
  31. {
  32. // Inject the custom factory if no other
  33. // replacement exists
  34. if (request.ActualFactory != null)
  35. return;
  36. var serviceType = request.ServiceType;
  37. // Skip any service requests for types that are generic type definitions
  38. if (serviceType.IsGenericTypeDefinition)
  39. return;
  40. // If the current service type is a generic type,
  41. // its type definition must match the given service type
  42. if (serviceType.IsGenericType && serviceType.GetGenericTypeDefinition() != _serviceType)
  43. return;
  44. // The service types must match
  45. if (!serviceType.IsGenericType && serviceType != _serviceType)
  46. return;
  47. // Inject the custom factory itself
  48. request.ActualFactory = _factory;
  49. }
  50. }
  51. }