PageRenderTime 9ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/src/LinFu.IoC/Factories/LazyFactory.cs

http://github.com/philiplaureano/LinFu
C# | 38 lines | 20 code | 5 blank | 13 comment | 3 complexity | d1b589affeab8ccda1828762f53c4dc9 MD5 | raw file
  1. using System;
  2. using LinFu.IoC.Interfaces;
  3. namespace LinFu.IoC.Factories
  4. {
  5. /// <summary>
  6. /// Represents an <see cref="IFactory" /> class that instantiates a factory only on request.
  7. /// </summary>
  8. public class LazyFactory : IFactory
  9. {
  10. private readonly Func<IFactoryRequest, IFactory> _getFactory;
  11. private IFactory _realFactory;
  12. /// <summary>
  13. /// Instantiates the class with the factory functor method.
  14. /// </summary>
  15. /// <param name="getFactory">The functor that will be responsible for instantiating the actual factory.</param>
  16. public LazyFactory(Func<IFactoryRequest, IFactory> getFactory)
  17. {
  18. _getFactory = getFactory;
  19. }
  20. /// <summary>
  21. /// Instantiates the actual factory instance and uses it to instantiate the target service type.
  22. /// </summary>
  23. /// <param name="request">The <see cref="IFactoryRequest" /> that describes the service to be created.</param>
  24. /// <returns>A valid service instance.</returns>
  25. public object CreateInstance(IFactoryRequest request)
  26. {
  27. // Create the factory if necessary
  28. if (_realFactory == null)
  29. _realFactory = _getFactory(request);
  30. return _realFactory == null ? null : _realFactory.CreateInstance(request);
  31. }
  32. }
  33. }