PageRenderTime 13ms CodeModel.GetById 10ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.AOP.Interfaces/TypeActivatorRegistry.cs

http://github.com/philiplaureano/LinFu
C# | 51 lines | 28 code | 7 blank | 16 comment | 9 complexity | 6198a29ca443fb0e7d263c23b8b4935a MD5 | raw file
 1using System;
 2
 3namespace LinFu.AOP.Interfaces
 4{
 5    /// <summary>
 6    ///     Represents a registry that allows users to statically register <see cref="ITypeActivator" />
 7    ///     instances.
 8    /// </summary>
 9    public static class TypeActivatorRegistry
10    {
11        private static readonly object _lock = new object();
12        private static ITypeActivator _activator;
13
14        /// <summary>
15        ///     Obtains an activator for the given <paramref name="context" />.
16        /// </summary>
17        /// <param name="context">The <see cref="ITypeActivationContext" /> instance that describes the object to be created.</param>
18        /// <returns>A method activator.</returns>
19        public static ITypeActivator GetActivator(ITypeActivationContext context)
20        {
21            if (context == null)
22                throw new ArgumentNullException("context");
23
24            // Use the static activator by default
25            var currentActivator = _activator;
26
27            // Use the activator attached to the target if it exists
28            var host = context.Target as IActivatorHost;
29            if (host != null && host.Activator != null)
30                currentActivator = host.Activator;
31
32            if (currentActivator != null && currentActivator.CanActivate(context))
33                return currentActivator;
34
35            return null;
36        }
37
38        /// <summary>
39        ///     Sets the <see cref="ITypeActivator" /> that will be used to
40        ///     instantiate object instances.
41        /// </summary>
42        /// <param name="activator">The <see cref="ITypeActivator" /> that will instantiate types.</param>
43        public static void SetActivator(ITypeActivator activator)
44        {
45            lock (_lock)
46            {
47                _activator = activator;
48            }
49        }
50    }
51}