PageRenderTime 81ms CodeModel.GetById 40ms app.highlight 2ms RepoModel.GetById 38ms app.codeStats 0ms

/src/LinFu.IoC/Factories/LazyFactoryOfT.cs

http://github.com/philiplaureano/LinFu
C# | 49 lines | 27 code | 9 blank | 13 comment | 4 complexity | 4bd500f98707191035a06da05a1922dd MD5 | raw file
 1using System;
 2using LinFu.IoC.Interfaces;
 3
 4namespace LinFu.IoC.Factories
 5{
 6    /// <summary>
 7    ///     Represents a factory that returns strongly-typed IFactory instances.
 8    /// </summary>
 9    /// <typeparam name="T">The service type to be created.</typeparam>
10    public class LazyFactory<T> : IFactory<T>, IFactory
11    {
12        private readonly Func<IFactoryRequest, IFactory> _getFactory;
13
14        /// <summary>
15        ///     Initializes the factory with the given <paramref name="getFactory" /> functor.
16        /// </summary>
17        /// <param name="getFactory">The functor that will instantiate the actual factory instance.</param>
18        public LazyFactory(Func<IFactoryRequest, IFactory> getFactory)
19        {
20            _getFactory = getFactory;
21        }
22
23
24        object IFactory.CreateInstance(IFactoryRequest request)
25        {
26            IFactory<T> thisFactory = this;
27            return thisFactory.CreateInstance(request);
28        }
29
30
31        /// <summary>
32        ///     Instantiates the service type using the actual factory.
33        /// </summary>
34        /// <param name="request">The <see cref="IFactoryRequest" /> instance that describes the service to be created.</param>
35        /// <returns></returns>
36        public T CreateInstance(IFactoryRequest request)
37        {
38            if (_getFactory == null)
39                throw new NotImplementedException();
40
41            var factory = _getFactory(request) as IFactory<T>;
42
43            if (factory == null)
44                return default(T);
45
46            return factory.CreateInstance(request);
47        }
48    }
49}