title: Loading Interface in DLL Dynamically
body: <p>I was trying to learn how to dynamically load DLL into a C# program.  The idea is that the DLL will contain an interface and several different implementations of the interface so that if I want to add new implementations I don't have to recompile my whole project.</p>
  
  <p>So I created this test.  Here is my DLL file:</p>
  
  <pre><code>namespace TestDLL
  {
    public interface Action
    {
      void DoAction();
    }
  
    public class PrintString : Action
    {
      public void DoAction()
      {
        Console.WriteLine("Hello World!");
      }
    }
  
    public class PrintInt : Action
    {
      public void DoAction()
      {
        Console.WriteLine("Hello 1!");
      }
    }
  }
  </code></pre>
  
  <p>And in my main program I tried to do something like this:</p>
  
  <pre><code>static void Main(string[] args)
  {
    List&lt;Action&gt; actions = new List&lt;Action&gt;();
    Assembly myDll = Assembly.LoadFrom("TestDLL.dll");
    Type[] types = myDll.GetExportedTypes();
  
    for (int i = 0; i &lt; types.Length; i++)
    {
      Type type = types[i];
      if (type.GetInterface("TestDLL.Action") != null  &amp;&amp; type != null)
      {
          Action new_action = myDll.CreateInstance(type.FullName) as Action;
          if (new_action != null)
            actions.Add(new_action);
          else
            Console.WriteLine("New Action is NULL");
      }
    }
  
    foreach (Action action in actions)
      action.DoAction();
  }
  </code></pre>
  
  <p>And the problem I am having is, even though </p>
  
  <pre><code>type.FullName
  </code></pre>
  
  <p>contains the right value ("TestDLL.PrintString", etc), </p>
  
  <p>the line</p>
  
  <pre><code>myDll.CreateInstance(type.FullName) as Action
  </code></pre>
  
  <p>always returns null.</p>
  
  <p>I am not exactly sure what the problem is, or how I could work around it.  </p>
  
  <p>As in the example, I would like to be able to add new implementations of Action to the DLL, and have the main Program invoke DoAction() on each of these implementation, without having to recompile the original program.  Hope this makes sense!</p>