PageRenderTime 215ms CodeModel.GetById 81ms app.highlight 7ms RepoModel.GetById 121ms app.codeStats 1ms

/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
 1using System;
 2using LinFu.IoC.Interfaces;
 3
 4namespace LinFu.IoC.Factories
 5{
 6    /// <summary>
 7    ///     A factory that creates a unique service instance every time
 8    ///     the <see cref="CreateInstance" /> method is called.
 9    /// </summary>
10    /// <typeparam name="T">The type of service to instantiate.</typeparam>
11    public class OncePerRequestFactory<T> : BaseFactory<T>
12    {
13        private readonly Func<IFactoryRequest, T> _createInstance;
14        private readonly Type _serviceType;
15
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>OncePerRequestFactory&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 OncePerRequestFactory&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 OncePerRequestFactory(Func<IFactoryRequest, T> createInstance)
38        {
39            _createInstance = createInstance;
40            _serviceType = typeof(T);
41        }
42
43        /// <summary>
44        ///     This method creates a new service instance every time
45        ///     it is invoked.
46        /// </summary>
47        /// <param name="request">The <see cref="IFactoryRequest" /> instance that describes the requested service.</param>
48        /// <returns>A non-null object reference.</returns>
49        public override T CreateInstance(IFactoryRequest request)
50        {
51            return _createInstance(request);
52        }
53    }
54}