/src/LinFu.IoC/Factories/OncePerRequestFactory.cs

http://github.com/philiplaureano/LinFu · C# · 54 lines · 19 code · 3 blank · 32 comment · 0 complexity · 124d9ee762459bdbdaa98127a7a69a91 MD5 · raw file

  1. using System;
  2. using LinFu.IoC.Interfaces;
  3. namespace LinFu.IoC.Factories
  4. {
  5. /// <summary>
  6. /// A factory that creates a unique service instance every time
  7. /// the <see cref="CreateInstance" /> method is called.
  8. /// </summary>
  9. /// <typeparam name="T">The type of service to instantiate.</typeparam>
  10. public class OncePerRequestFactory<T> : BaseFactory<T>
  11. {
  12. private readonly Func<IFactoryRequest, T> _createInstance;
  13. private readonly Type _serviceType;
  14. /// <summary>
  15. /// Initializes the factory class using the <paramref name="createInstance" />
  16. /// parameter as a factory delegate.
  17. /// </summary>
  18. /// <example>
  19. /// The following is an example of initializing a <c>OncePerRequestFactory&lt;T&gt;</c>
  20. /// type:
  21. /// <code>
  22. /// // Define the factory delegate
  23. /// Func&lt;IFactoryRequest, ISomeService&gt; createService = container=>new SomeServiceImplementation();
  24. ///
  25. /// // Create the factory
  26. /// var factory = new OncePerRequestFactory&lt;ISomeService&gt;(createService);
  27. ///
  28. /// // Use the service instance
  29. /// var service = factory.CreateInstance(null);
  30. ///
  31. /// // ...
  32. /// </code>
  33. /// </example>
  34. /// <param name="createInstance">The delegate that will be used to create each new service instance.</param>
  35. public OncePerRequestFactory(Func<IFactoryRequest, T> createInstance)
  36. {
  37. _createInstance = createInstance;
  38. _serviceType = typeof(T);
  39. }
  40. /// <summary>
  41. /// This method creates a new service instance every time
  42. /// it is invoked.
  43. /// </summary>
  44. /// <param name="request">The <see cref="IFactoryRequest" /> instance that describes the requested service.</param>
  45. /// <returns>A non-null object reference.</returns>
  46. public override T CreateInstance(IFactoryRequest request)
  47. {
  48. return _createInstance(request);
  49. }
  50. }
  51. }