Unplug
Unplug

Reputation: 709

Load a class dynamically in C#

I am trying to load a class (say Class1:Interface ) without knowing its name from an assembly. My code looks like this:

Assembly a = Assembly.LoadFrom("MyDll.dll");
Type t = (Type)a.GetTypes()[0];
(Interface) classInstance = (Interface) (ClasActivator.CreateInstance(t);

Based on the articles I found online and MSDN, GetTypes()[0] is suppose to return Class1 (there is only one class in MyDll.dll). However, my code returns Class1.Properties.Settings. So line 3 creates an exception:

Unable to cast object of type 'Class1.Properties.Settings' to type Namespace.Interface'.

I really do not know why and how to fix this problem.

Upvotes: 1

Views: 3753

Answers (2)

McGarnagle
McGarnagle

Reputation: 102743

Just check to find the first that implements the interface:

Type t = a.GetTypes()
  .FirstOrDefault(type => type.GetInterface(typeof(Interface).FullName) != null);

Upvotes: 2

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

The assembly can hold more than one type (you likely have a Settings.settings file in the dll, it creates a class under the hood in the Settings.Designer.cs file), you only get the first class in your code which in your case turned out to be the Settings class, you need to go through all the types and search for the ones that have the interface you need.

Assembly asm = Assembly.LoadFrom("MyDll.dll");
Type[] allTypes = asm.GetTypes();
foreach (Type type in allTypes)
{
    // Only scan objects that are not abstract and implements the interface
    if (!type.IsAbstract && typeof(IMyInterface).IsAssignableFrom(type));
    {
        // Create a instance of that class...
        var inst = (IMyInterface)Activator.CreateInstance(type);

        //do your work here, may be called more than once if more than one class implements IMyInterface
    }
}

Upvotes: 3

Related Questions