/src/LinFu.IoC/Configuration/FluentInterfaces/GenerateFactory.cs

http://github.com/philiplaureano/LinFu · C# · 76 lines · 35 code · 9 blank · 32 comment · 0 complexity · a499c558c3d84d507c0733fc194cef1b MD5 · raw file

  1. using System;
  2. using LinFu.IoC.Factories;
  3. using LinFu.IoC.Interfaces;
  4. namespace LinFu.IoC.Configuration
  5. {
  6. /// <summary>
  7. /// Represents a fluent class that allows
  8. /// users to create specific types of factories.
  9. /// </summary>
  10. /// <typeparam name="TService">The type of service being created.</typeparam>
  11. internal class GenerateFactory<TService> : IGenerateFactory<TService>
  12. {
  13. private readonly InjectionContext<TService> _context;
  14. /// <summary>
  15. /// Instantiates the class using the given
  16. /// <paramref name="context" />.
  17. /// </summary>
  18. /// <param name="context">
  19. /// The <see cref="InjectionContext{T}" /> instance
  20. /// which will contain the information necessary to build a fluent command.
  21. /// </param>
  22. internal GenerateFactory(InjectionContext<TService> context)
  23. {
  24. _context = context;
  25. }
  26. /// <summary>
  27. /// Creates a singleton factory.
  28. /// </summary>
  29. /// <seealso cref="SingletonFactory{T}" />
  30. public void AsSingleton()
  31. {
  32. AddFactory(adapter => new SingletonFactory<TService>(adapter));
  33. }
  34. /// <summary>
  35. /// Creates a once per thread factory.
  36. /// </summary>
  37. /// <seealso cref="OncePerThreadFactory{T}" />
  38. public void OncePerThread()
  39. {
  40. AddFactory(adapter => new OncePerThreadFactory<TService>(adapter));
  41. }
  42. /// <summary>
  43. /// Creates a once per request factory.
  44. /// </summary>
  45. /// <seealso cref="OncePerRequestFactory{T}" />
  46. public void OncePerRequest()
  47. {
  48. AddFactory(adapter => new OncePerRequestFactory<TService>(adapter));
  49. }
  50. /// <summary>
  51. /// Adds a factory to the container by using the
  52. /// <paramref name="createFactory" /> delegate to
  53. /// create the actual <see cref="IFactory{T}" />
  54. /// instance.
  55. /// </summary>
  56. /// <param name="createFactory">The delegate that will create the actual factory instance.</param>
  57. private void AddFactory(Func<Func<IFactoryRequest, TService>,
  58. IFactory<TService>> createFactory)
  59. {
  60. var container = _context.Container;
  61. var adapter = _context.FactoryMethod.CreateAdapter();
  62. var factory = createFactory(adapter);
  63. var serviceName = _context.ServiceName;
  64. container.AddFactory(serviceName, factory);
  65. }
  66. }
  67. }