PageRenderTime 15ms CodeModel.GetById 12ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.Reflection/BasePluginLoader.cs

http://github.com/philiplaureano/LinFu
C# | 57 lines | 32 code | 4 blank | 21 comment | 2 complexity | 7e0fed204ecfc7f9ca05a0ecea9bd7d6 MD5 | raw file
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5
 6namespace LinFu.Reflection
 7{
 8    /// <summary>
 9    ///     Implements the basic functionality of a plugin loader.
10    /// </summary>
11    /// <typeparam name="TTarget">The target type being configured.</typeparam>
12    /// <typeparam name="TAttribute">The attribute type that will be used to mark a type as a plugin.</typeparam>
13    public abstract class BasePluginLoader<TTarget, TAttribute> : IActionLoader<ILoader<TTarget>, Type>
14        where TAttribute : Attribute
15    {
16        /// <summary>
17        ///     Determines if the plugin loader can load the <paramref name="inputType" />.
18        /// </summary>
19        /// <param name="inputType">The target type that might contain the target <typeparamref name="TAttribute" /> instance.</param>
20        /// <returns><c>true</c> if the type can be loaded; otherwise, it returns <c>false</c>.</returns>
21        public virtual bool CanLoad(Type inputType)
22        {
23            try
24            {
25                var attributes = inputType.GetCustomAttributes(typeof(TAttribute), true)
26                    .Cast<TAttribute>();
27
28                // The type must have a default constructor
29                var defaultConstructor = inputType.GetConstructor(new Type[0]);
30                if (defaultConstructor == null)
31                    return false;
32
33                // The target must implement the ILoaderPlugin<TTarget> interface
34                // and be marked with the custom attribute
35                return attributes.Count() > 0;
36            }
37            catch (TypeInitializationException)
38            {
39                // Ignore the error
40                return false;
41            }
42            catch (FileNotFoundException)
43            {
44                // Ignore the error
45                return false;
46            }
47        }
48
49        /// <summary>
50        ///     Generates a set of <see cref="Action{TTarget}" /> instances
51        ///     using the given <paramref name="input" />.
52        /// </summary>
53        /// <param name="input">The input that will be used to configure the target.</param>
54        /// <returns>A set of <see cref="Action{TTarget}" /> instances. This cannot be <c>null</c>.</returns>
55        public abstract IEnumerable<Action<ILoader<TTarget>>> Load(Type input);
56    }
57}