/src/LinFu.IoC/Factories/LazyFactoryOfT.cs

http://github.com/philiplaureano/LinFu · C# · 49 lines · 27 code · 9 blank · 13 comment · 4 complexity · 4bd500f98707191035a06da05a1922dd MD5 · raw file

  1. using System;
  2. using LinFu.IoC.Interfaces;
  3. namespace LinFu.IoC.Factories
  4. {
  5. /// <summary>
  6. /// Represents a factory that returns strongly-typed IFactory instances.
  7. /// </summary>
  8. /// <typeparam name="T">The service type to be created.</typeparam>
  9. public class LazyFactory<T> : IFactory<T>, IFactory
  10. {
  11. private readonly Func<IFactoryRequest, IFactory> _getFactory;
  12. /// <summary>
  13. /// Initializes the factory with the given <paramref name="getFactory" /> functor.
  14. /// </summary>
  15. /// <param name="getFactory">The functor that will instantiate the actual factory instance.</param>
  16. public LazyFactory(Func<IFactoryRequest, IFactory> getFactory)
  17. {
  18. _getFactory = getFactory;
  19. }
  20. object IFactory.CreateInstance(IFactoryRequest request)
  21. {
  22. IFactory<T> thisFactory = this;
  23. return thisFactory.CreateInstance(request);
  24. }
  25. /// <summary>
  26. /// Instantiates the service type using the actual factory.
  27. /// </summary>
  28. /// <param name="request">The <see cref="IFactoryRequest" /> instance that describes the service to be created.</param>
  29. /// <returns></returns>
  30. public T CreateInstance(IFactoryRequest request)
  31. {
  32. if (_getFactory == null)
  33. throw new NotImplementedException();
  34. var factory = _getFactory(request) as IFactory<T>;
  35. if (factory == null)
  36. return default(T);
  37. return factory.CreateInstance(request);
  38. }
  39. }
  40. }