1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Dynamic Assembly Loading

Discussion in 'C#' started by Huggz, Apr 18, 2008.

  1. Huggz

    Huggz New Member

    Joined:
    Apr 18, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I'm trying to extend my CMS with a plugin interface to make extensibility a little easier to manage. I created 2 classes: an abstract base class (baseModule) containing a single abstract method Init() and a class that inherits from it (TestModule) and throws an exception when Init is called. In my Engine, I'm doing the following:

    Code:
                if (!module_dir.Exists) throw new Exception("Modules directory does not exist.");
                foreach (FileInfo f in module_dir.GetFiles("*.dll"))
                {
                    Type t = Assembly.LoadFile(f.FullName).GetType();
                    baseModule m = Activator.CreateInstance(t) as baseModule;
                    if (m == null)
                    {
                        throw new Exception("dll is not of type IModule");
                    }
                    module_list.Add(m);
                }
    
    Unfortunately when I hit Activator.CreateInstance, I get the error :

    "No parameterless constructor defined for this object."

    Any ideas what I'm doing wrong?
     
  2. excavator

    excavator New Member

    Joined:
    Apr 25, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    it seems that the variable t refer to "System.Reflection.Assembly" not to the dll you want to instantiate. below is a simple sample code about dynamic loading, you need to modify it to fit in your application.

    Code:
    private void LoadAssembly()
            {
                Assembly a = Assembly.LoadFile(filename);
                System.Type[] sts = a.GetTypes();
                foreach (System.Type st in sts)
                {
                    Object o = Activator.CreateInstance(st);
                    if (o != null)
                    {
                        Console.WriteLine(st.FullName + " Instantiated\n");
                        //proceed with type conversion here
                    }
                    else
                    {
                        Console.WriteLine(st.FullName + " NOT Instantiated\n");
                    }
                }                        
            }
    
    hope this help
     

Share This Page