PageRenderTime 35ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/LinFu.IoC/Factories/SingletonFactory.cs

http://github.com/philiplaureano/LinFu
C# | 69 lines | 30 code | 8 blank | 31 comment | 4 complexity | 7f7b13c0a6b0472884dbce59644d8809 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using LinFu.IoC.Interfaces;
  4. namespace LinFu.IoC.Factories
  5. {
  6. /// <summary>
  7. /// A factory that creates Singletons. Each service that this factory creates will only be created once per concrete
  8. /// type.
  9. /// </summary>
  10. /// <typeparam name="T">The type of service to instantiate.</typeparam>
  11. public class SingletonFactory<T> : BaseFactory<T>
  12. {
  13. private static readonly Dictionary<object, T> _instances = new Dictionary<object, T>();
  14. private static readonly object _lock = new object();
  15. private readonly Func<IFactoryRequest, T> _createInstance;
  16. /// <summary>
  17. /// Initializes the factory class using the <paramref name="createInstance" />
  18. /// parameter as a factory delegate.
  19. /// </summary>
  20. /// <example>
  21. /// The following is an example of initializing a <c>SingletonFactory&lt;T&gt;</c>
  22. /// type:
  23. /// <code>
  24. /// // Define the factory delegate
  25. /// Func&lt;IFactoryRequest, ISomeService&gt; createService = container=>new SomeServiceImplementation();
  26. ///
  27. /// // Create the factory
  28. /// var factory = new SingletonFactory&lt;ISomeService&gt;(createService);
  29. ///
  30. /// // Use the service instance
  31. /// var service = factory.CreateInstance(null);
  32. ///
  33. /// // ...
  34. /// </code>
  35. /// </example>
  36. /// <param name="createInstance">The delegate that will be used to create each new service instance.</param>
  37. public SingletonFactory(Func<IFactoryRequest, T> createInstance)
  38. {
  39. _createInstance = createInstance;
  40. }
  41. /// <summary>
  42. /// A method that creates a service instance as a singleton.
  43. /// </summary>
  44. /// <param name="request">The <see cref="IFactoryRequest" /> instance that describes the requested service.</param>
  45. /// <returns>A service instance as a singleton.</returns>
  46. public override T CreateInstance(IFactoryRequest request)
  47. {
  48. var key = new {request.ServiceName, request.ServiceType, request.Container};
  49. if (_instances.ContainsKey(key))
  50. return _instances[key];
  51. lock (_lock)
  52. {
  53. if (_instances.ContainsKey(key))
  54. return _instances[key];
  55. var result = _createInstance(request);
  56. if (result != null) _instances[key] = result;
  57. }
  58. return _instances[key];
  59. }
  60. }
  61. }