65.9K
CodeProject is changing. Read more.
Home

How Can You Load .NET Assemblies Dynamically

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.77/5 (7 votes)

Apr 1, 2008

CPOL

1 min read

viewsIcon

31261

downloadIcon

349

Not really new, but a solution

Introduction

This is my first English article, so excuse my horrible English.

The first time I started developing a .NET application, I had to load a DLL dynamically. I did not know how to do it, but I wrote a function to do that. The next time I need a function to load a DLL from an Interface, I copy the first function and change the parameters. After that, I load not only one DLL so we can have many. Copy the first function and change the parameters.

Hmm, wait a moment. There is a lot of space to do it in the generic way.

Background

The generic way means that you have, at designtime, no idea what objects at runtime you will work with.

public static class ModuleLoader<T>

Using the Code

Functionlist:

Load only one Module:

public static T LoadModule(Guid moduleId)
public static T LoadModule(Guid moduleId, string path)
public static T LoadModule(Guid moduleId, string path, string fileExtension)

Load a list of Modules:

public static List<T> LoadModuleList()
public static List<T> LoadModuleList(string path)
public static List<T> LoadModuleList(Guid moduleId, string path, string fileExtension)

When you want to load a list of Modules, I think you will use an Interface as T.

Example:

Loads all Assemblies that implement the IPlugIn Interface in the current Directory.

List<IPlugIn> pluginList = ModuleLoader<IPlugIn>.LoadModuleList();

Loads a given Assembly that implement the IPlugIn Interface in the current Directory. Where pluginId is the TypeGuid of the given PlugIn.

IPlugIn plugin = ModuleLoader<IPlugIn>.LoadModule(pluginId);

In the next article, I will explain how you can use the ModuleLoader with an AppDomain to load and unload at runtime.

History

  • 1st April, 2008: Initial post