Exemplo n.º 1
0
        public Component LoadComponent(string filePath)
        {
            FileInfo file = new FileInfo(filePath);

            // Preliminary check
            // must exist
            if (!file.Exists)
            {
                throw new PluginException(string.Format("File {0} does not exist. Cannot load Component.", filePath));
            }
            // must be a dll file
            if (!file.Extension.Equals(".dll"))
            {
                throw new PluginException(string.Format("File {0} is not a dll file. Cannot load Component.", filePath));
            }

            //Create a new assembly from the plugin file we're adding..
            Assembly  pluginAssembly = Assembly.LoadFrom(filePath);
            Component component      = null;

            //Next we'll loop through all the Types found in the assembly
            foreach (Type pluginType in pluginAssembly.GetTypes())
            {
                if (pluginType.IsPublic)        //Only look at public types
                {
                    if (!pluginType.IsAbstract) //Only look at non-abstract types
                    {
                        //Gets a type object of the interface we need the plugins to match
                        Type typeInterface = pluginType.GetInterface("Pic.Plugin.IPlugin", true);

                        //Make sure the interface we want to use actually exists
                        if (typeInterface != null)
                        {
                            //Create a new available plugin since the type implements the IPlugin interface
                            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
                            if (null != plugin)
                            {
                                component = new Component(plugin);

                                //Set the Plugin's host to this class which inherited IPluginHost
                                plugin.Host = this;

                                //Call the initialization sub of the plugin
                                plugin.Initialize();

                                //cleanup a bit
                                plugin = null;
                            }
                        }
                        typeInterface = null; //Mr. Clean
                    }
                }
            }
            pluginAssembly = null; //more cleanup

            // check that a component was actually created
            if (null == component)
            {
                throw new Pic.Plugin.PluginException(string.Format("Failed to load valid component from existing file {0}", filePath));
            }

            // insert component in cache for fast retrieval
            ComponentLoader.InsertInCache(component);

            return(component);
        }