PageRenderTime 102ms CodeModel.GetById 60ms app.highlight 3ms RepoModel.GetById 37ms app.codeStats 1ms

/src/LinFu.IoC/Factories/FactoryAdapter.cs

http://github.com/philiplaureano/LinFu
C# | 64 lines | 29 code | 10 blank | 25 comment | 6 complexity | c62399b3ff4de5231aebbbf7ba150230 MD5 | raw file
 1using LinFu.IoC.Interfaces;
 2
 3namespace LinFu.IoC
 4{
 5    /// <summary>
 6    ///     An adapter that converts strongly-typed IFactory&lt;T&gt;
 7    ///     instances into an equivalent IFactory instance.
 8    /// </summary>
 9    /// <typeparam name="T">The service type to create.</typeparam>
10    public class FactoryAdapter<T> : IFactory, IFactory<T>
11    {
12        private readonly object _factory;
13
14        /// <summary>
15        ///     Creates the factory adapter using the given
16        ///     IFactory&lt;T&gt; instance.
17        /// </summary>
18        /// <param name="factory">
19        ///     The factory instance that
20        ///     will be called every time the <see cref="IFactory.CreateInstance" /> method
21        ///     is called.
22        /// </param>
23        public FactoryAdapter(object factory)
24        {
25            _factory = factory;
26        }
27
28        /// <summary>
29        ///     The factory that will create the service instance.
30        /// </summary>
31        public IFactory<T> Factory => _factory as IFactory<T>;
32
33
34        /// <summary>
35        ///     Overridden. Uses the strongly-typed factory
36        ///     to create the service instance every time
37        ///     the <see cref="IFactory.CreateInstance" /> method
38        ///     is called.
39        /// </summary>
40        /// <param name="request">The <see cref="IFactoryRequest" /> instance that describes the requested service.</param>
41        /// <returns>An object instance that represents the service to be created. This cannot be <c>null</c>.</returns>
42        public object CreateInstance(IFactoryRequest request)
43        {
44            if (_factory == null)
45                return default(T);
46
47            var factory = _factory as IFactory<T>;
48            if (factory == null)
49                return default(T);
50
51            return factory.CreateInstance(request);
52        }
53
54
55        T IFactory<T>.CreateInstance(IFactoryRequest request)
56        {
57            var factory = _factory as IFactory<T>;
58            if (factory == null)
59                return default(T);
60
61            return factory.CreateInstance(request);
62        }
63    }
64}