Exception thrown when calling Assembly.CreateInstance Method


i have 2 assemblies which both has a class name Source.
i compile them seperately and place the dlls in the target application directory.
lets call them ass1.dll and ass2.dll.

i want to create an instance of those 2 objects so i use Assembly.CreateInstance to do so, as follow:

string [] strFiles = System.IO.Directory.GetFiles(System.IO.Directory.GetParent(strCurrentDirectory)+"//Services");
foreach(string strFile in strFiles)
      Assembly asm = Assembly.LoadFile(strFile);
foreach(Type t in asm.GetTypes())
//i look for the "source" class
if(t.Name != "Source")

object obj = null;
//t.ToString() contains namespace + class name

                  obj = asm.CreateInstance(t.ToString(), true,                                                                              BindingFlags.Public | BindingFlags.Instance,                                                                              null, new object[]{/*some argument*/}, null, null);

                                                catch(Exception e)
                                                      string str = e.Message;

the exception massage is:
{"Item has already been added.  Key in dictionary: \"Source\"  Key being added: \"Source\"" }

what that means?

why i always get an exception in the second time when i'm trying to create the instance, despite the fact that the class is from a different namespace?

LVL 42
Meir RivkinFull stack Software EngineerAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

dunglaConnect With a Mentor Commented:
when you call asm.CreateInstance it will throw exception or when you try to add a value to hashtable?
Meir RivkinFull stack Software EngineerAuthor Commented:
on CreateInstance()

the hastable code is being performed in case the CreateInstance succeed.
Meir RivkinFull stack Software EngineerAuthor Commented:
i was trying to use tyhe following code instead but i got the same exception:

ObjectHandle objh = Activator.CreateInstanceFrom(strFile, t.ToString());
Object obj = objh.Unwrap();
Meir RivkinFull stack Software EngineerAuthor Commented:
i found the problem,

the instance being created is a property grid derived class which register itself in a singleton property manager which holds a hashtable (thats why the exception with the dictionary key).

10x for the help
All Courses

From novice to tech pro — start learning today.