Mark
Mark

Reputation: 107

Dynamically loaded dll interface function returns usercontrol

For a minor project I have created a basic interface which is used to create plugins. This interface has a function that returns a UserControl. However when this is called and the UserControl is added to a panel nothing shows in the panel (even if .Show() or Visibility = true is set). I had assumed that when the assembly.CreateInstance() is called this creates instances of any objects in the class.

Is this not the case? Is a CreateInstance() required to be called on all UserControls before they can be used in this way?

public interface IMyInterface
{
    System.Windows.Forms.UserControl GetConfigurationControl();
}

Implemented class in the dll:

public class myClass: IMyInterface
{
    return new myUserControl();
}

Loaded all dlls in the directory:

private void LoadPlugins()
{
 foreach (string file in Directory.GetFiles(Application.StartupPath+"/plugins/", "*.dll",       SearchOption.AllDirectories))
        {
            Assembly assembly = Assembly.LoadFile(file);
            var types = from t in assembly.GetTypes()
                    where t.IsClass &&
                    (t.GetInterface(typeof(IMyInterface).Name) != null)
                    select t;
            foreach (Type t in types)
            {
                IMyInterface plugin = (IMyInterface)assembly.CreateInstance(t.FullName, true);
                this.pluginsList.Add(plugin); //just a list of the plugins
            }
        }
    this.AddPluginUserControls();
 }    

Add the user controls to a panel:

 private AddPluginUserControls()
 {
     foreach (IMyInterface plugin in pluginsList)
     {
          myPanel.Controls.Add(plugin.GetConfigurationControl());
     }
 }

I am aware of other full plugin architectures however this is more a learning application. Thanks!

UserControl:

public partial class myUserControl: UserControl
{
    public myUserControl()
    {
        InitializeComponent(); // couple of labels, vs generated.
    }
}

Upvotes: 3

Views: 582

Answers (2)

Mark
Mark

Reputation: 107

Right found it! It was an issue with using a System.Windows.Forms.FlowLayoutPanel and the UserControl having the DockStyle set to fill. Thanks for all answers!

Upvotes: 0

YK1
YK1

Reputation: 7612

Make sure two things 1. in default myUserControl constructor, InitializeComponent() is called which will instantiate and add your labels to the control. 2. Give some width and height to the user control before adding to panel.

Upvotes: 1

Related Questions