Free mag vol1 | Page 654

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING else if(!LoadExternalModule(dlg.FileName)) MessageBox.Show("Nothing implements IAppFunctionality!"); } } The LoadExternalModule() method performs the following tasks: • Dynamically loads the selected assembly into memory • Determines whether the assembly contains any types implementing IAppFunctionality • Creates the type using late binding If a type implementing IAppFunctionality is found, the DoIt() method is called, and the fully qualified name of the type is added to the ListBox (note that the foreach loop will iterate over all types in the assembly to account for the possibility that a single assembly has multiple snap-ins). private bool LoadExternalModule(string path) { bool foundSnapIn = false; Assembly theSnapInAsm = null; try { // Dynamically load the selected assembly. theSnapInAsm = Assembly.LoadFrom(path); } catch(Exception ex) { MessageBox.Show(ex.Message); return foundSnapIn; } // Get all IAppFunctionality-compatible classes in assembly. var theClassTypes = from t in theSnapInAsm.GetTypes() where t.IsClass && (t.GetInterface("IAppFunctionality") != null) select t; // Now, create the object and call DoIt() method. foreach (Type t in theClassTypes) { foundSnapIn = true; // Use late binding to create the type. IAppFunctionality itfApp = (IAppFunctionality)theSnapInAsm.CreateInstance(t.FullName, true); itfApp.DoIt(); lstLoadedSnapIns.Items.Add(t.FullName); } return foundSnapIn; } At this point, you can run your application. When you select the CSharpSnapIn.dll or VbSnapIn.dll assemblies, you should see the correct message displayed. The final task is to display the metadata provided by the [CompanyInfo] attribute. To do so, update LoadExternalModule() to call a new helper 596