Axiom.Core.ObjectCreator.CreateInstance C# (CSharp) Method

CreateInstance() public method

public CreateInstance ( ) : T
return T
        public T CreateInstance<T>() where T : class
        {
            var type = this._type;
            var assembly = this._assembly;
#if !(XBOX || XBOX360)
            // Check interfaces or Base type for casting purposes
            if (type.GetInterface(typeof(T).Name, false) != null || type.BaseType.Name == typeof(T).Name)
#else
			bool typeFound = false;
			for (int i = 0; i < type.GetInterfaces().GetLength(0); i++)
			{
				if ( type.GetInterfaces()[ i ] == typeof( T ) )
				{
					typeFound = true;
					break;
				}
			}

			if ( typeFound )
#endif
            {
                try
                {
                    return (T)Activator.CreateInstance(type);
                }
                catch (Exception e)
                {
                    LogManager.Instance.Write("Failed to create instance of {0} of type {0} from assembly {1}", typeof(T).Name, type, assembly.FullName);
                    LogManager.Instance.Write(LogManager.BuildExceptionString(e));
                }
            }
            return null;
        }
    }

Usage Example

Beispiel #1
0
        /// <summary>
        ///		Loads a plugin of the given class name from the given assembly, and calls Initialize() on it.
        ///		This function does NOT add the plugin to the PluginManager's
        ///		list of plugins.
        /// </summary>
        /// <returns>The loaded plugin.</returns>
        private static IPlugin LoadPlugin(ObjectCreator creator)
        {
            try
            {
                // Avoid duplicates of plugins of the same type.
                if (_plugins.Count > 0)
                {
                    var byTypePlugins = from p in _plugins
                                        where p.GetType() == creator.CreatedType
                                        select p;

                    if (byTypePlugins.Count() > 0)
                    {
                        LogManager.Instance.Write("{0} already loaded.", creator.GetAssemblyTitle());
                        return(null);
                    }
                }

                // create and start the plugin
                var plugin = creator.CreateInstance <IPlugin>();

                if (plugin == null)
                {
                    LogManager.Instance.Write("Failed to load plugin: {0}", creator.GetAssemblyTitle());
                    return(null);
                }

                plugin.Initialize();

                LogManager.Instance.Write("Loaded plugin: {0}", creator.GetAssemblyTitle());

                return(plugin);
            }
            catch (Exception ex)
            {
                LogManager.Instance.Write(LogManager.BuildExceptionString(ex));
            }

            return(null);
        }