Load Assembly at runtime from another dll in C#

This example shows how to load a specialized version of Component implementation from from another dll during runtime. Define an interface in a Common project

namespace MyCompany.Common
{
  public interface Component
  {
    void Execute();
  }
}

Create specialized library that will be loaded at runtime and add reference to Common project.

using MyCompany.Common;
namespace MyCompany.Custom
{
  public class SampleComponent : Component
  {
    public void Execute()
    {
      Console.WriteLine("Sample Component");
    }
  }
}

Create your Console/Windows project and add a reference to Common project. Do not add reference to Custom one as this assembly will be loaded at runtime.

using MyCompany.Common;
namespace MyCompany.MyProgram
{
  static class Program
  {
    public static void Main()
    {
      string path = @"{your.dll.directory}\MyCompany.Custom.dll";
      Assembly a = Assembly.LoadFile(path);
      Component c = (Component)a.CreateInstance("MyCompany.Common.SampleComponent");
      c.Execute();
    }
  }
}

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#