コード例 #1
0
        /// <summary>
        ///     Creates and returns an instance of the specified <see cref="IManager"/> Type.
        /// </summary>
        /// <typeparam name="T">The Type of the Manager to instantiate.</typeparam>
        /// <returns>The instantiated IManager.</returns>
        /// <exception cref="MissingMethodException">Thrown when a reflected method can not be found.</exception>
        /// <exception cref="ManagerInstantiationException">
        ///     Thrown when an error is encountered while instantiating the specified Manager Type.
        /// </exception>
        private T InstantiateManager <T>()
            where T : IManager
        {
            logger.EnterMethod(xLogger.TypeParams(typeof(T)));
            logger.Trace("Creating new instance of '" + typeof(T).Name + "'...");

            T instance;

            try
            {
                // use reflection to locate the static Instantiate() method in the target class, then check to make sure it was found.
                MethodInfo method = typeof(T).GetMethod("Instantiate", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);

                // use reflection to locate the static ResolveManagerDependencies() method, create a generic version with the type
                // for the manager we are trying to instantiate, then invoke it.
                MethodInfo      resolveMethod        = GetType().GetMethod("ResolveManagerDependencies", BindingFlags.NonPublic | BindingFlags.Instance);
                MethodInfo      genericResolveMethod = resolveMethod.MakeGenericMethod(typeof(T));
                List <IManager> resolvedDependencies = (List <IManager>)genericResolveMethod.Invoke(this, new object[] { });

                // invoke the Instantiate() method and pass the resolved dependencies from the step above. store the result in
                // instance, then check to make sure it is not null and ensure that it implements IManager.
                instance = (T)method.Invoke(null, resolvedDependencies.ToArray());

                logger.Trace("Successfully instantiated '" + instance.GetType().Name + "'.");
            }
            catch (Exception ex)
            {
                logger.Exception(ex);
                throw new ManagerInstantiationException("Error instantiating Manager '" + typeof(T).Name + "'.  See inner exception for details.", ex);
            }

            logger.ExitMethod();
            return(instance);
        }