PageRenderTime 32ms CodeModel.GetById 29ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.IoC/Factories/LazyFactory.cs

http://github.com/philiplaureano/LinFu
C# | 38 lines | 20 code | 5 blank | 13 comment | 3 complexity | d1b589affeab8ccda1828762f53c4dc9 MD5 | raw file
 1using System;
 2using LinFu.IoC.Interfaces;
 3
 4namespace LinFu.IoC.Factories
 5{
 6    /// <summary>
 7    ///     Represents an <see cref="IFactory" /> class that instantiates a factory only on request.
 8    /// </summary>
 9    public class LazyFactory : IFactory
10    {
11        private readonly Func<IFactoryRequest, IFactory> _getFactory;
12        private IFactory _realFactory;
13
14        /// <summary>
15        ///     Instantiates the class with the factory functor method.
16        /// </summary>
17        /// <param name="getFactory">The functor that will be responsible for instantiating the actual factory.</param>
18        public LazyFactory(Func<IFactoryRequest, IFactory> getFactory)
19        {
20            _getFactory = getFactory;
21        }
22
23
24        /// <summary>
25        ///     Instantiates the actual factory instance and uses it to instantiate the target service type.
26        /// </summary>
27        /// <param name="request">The <see cref="IFactoryRequest" /> that describes the service to be created.</param>
28        /// <returns>A valid service instance.</returns>
29        public object CreateInstance(IFactoryRequest request)
30        {
31            // Create the factory if necessary
32            if (_realFactory == null)
33                _realFactory = _getFactory(request);
34
35            return _realFactory == null ? null : _realFactory.CreateInstance(request);
36        }
37    }
38}