Click here to Skip to main content
Click here to Skip to main content

Dynamic Loading Made Simple

By , 24 Mar 2008
 

Introduction

Dynamic Loading is the process of loading code and using it at run time rather than at compile time. Why use it? Simple, dynamic loading makes the process of modifying a program and adding extra functionality later on easier (especially by third-party vendors). Furthermore it makes larger projects far more managable since each section of code functionality is seperate from each other. Many applications use this technique for implementation of plugins, e.g. Visual Studio and CIRIP (see demo link).

The included source shows how to load classes from dll files (dynamical link libraries) at runtime based upon a particular interface.

The Code

public static List<object> LoadAssemblies(String path, String interfaceName, bool recursive)
{
    List<object> output = new List<object>();

    String[] files = new String[0];
    if (recursive)
    {
        files = Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories);
    }
    else
    {
        files = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly);
    }

    foreach (String filename in files)
    {
        Console.WriteLine("Loading " + filename);
        try
        {
            Assembly assembly = Assembly.LoadFrom(filename);

            foreach (Type t in assembly.GetTypes())
            {
                if (t.IsClass && !t.IsAbstract && t.GetInterface(interfaceName) != null)
                {
                    output.Add(Activator.CreateInstance(t));
                }
            }
        }
        catch (Exception err)
        {
            Console.WriteLine("Loading fail:" + err.ToString());
        }
        finally
        {
            Console.WriteLine("Loading complete");
        }
    }

    return output;
}

The LoadAssemblies method loads in a single instance of each class implementing interfaceName in dll files found at the path (or in deeper folders if recursive = true is specified).

Using the Code

To use the code the following steps must be taken;

  1. Create an application where dynamic loading support is required
  2. Create a new class library (dll) with a copy of the interface all plugins will support
  3. Create an explit link from the application to the interface library
  4. Create new class libraries (dlls) containing classes which implement the interface
  5. Add the included code into the application
  6. During the load in period of the application call LoadAssemblies; using the path to the dlls & the fully qualified name of the interface (e.g. DNBSoft.InterfaceA).
  7. Foreach of the returned objects (cast to the interface once returned as the List<object>) call the relevant methods to link the plugin to the application.

Points of Interest

Did you learn anything interesting/fun/annoying while writing the code? Did you do anything particularly clever or wild or zany? No and no, however plugin support is VERY useful, and once you get the hang of it you'll use it alot.

It's the way forward!!!

History

Version 1.0.0.0 - The one and only release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Derek Bartram
Software Developer Rail Research UK
United Kingdom United Kingdom
Member
I originally studied for a masters in engineering of software engineering at The University of Birmingham during 2000-2004, of which I received a 2:1. I continued at Birmingham University working with Civil Engineering and Rail Research UK where I am currently in my final year of a 3 year PhD project developing a Computational Intelligent Approach to Railway Intervention Planning. Although my work has a significant focus on railway engineering and associated practices much of my work is with data mining (on SQL Server 2008) and computational intelligence (CI) techniques. My key areas of expertise in CI are clustering algorithms (including Rival Penalised Competitive Learning) and evolutionary algorithms.
 
Outside of my formal work I enjoy testing the latest technologies such as .NET 3.5 and the many frameworks of which it comprises (mainly WPF). I have several projects on the go including a .NET and DirectX port of Quake 3 and many utility libraries. I also maintain an extensive website coded in Cold Fusion which is regularly updated; more information is available about me there.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membereduMolaMazo21 Oct '11 - 0:55 
GeneralUse AppDomainmemberYitzhak Gootvilig10 Apr '08 - 3:25 
NewsAll DLL's get locked when loaded and it's clasess get instantiated, so no DLL can be dropped while the system is running!memberAndyHo7 Apr '08 - 14:55 
Hi there
 
I have been using this shema for a long time, I once built a framework who runs as a windows-service and monitors a directory for some new XML as (*.config files) to see what classes it needs to instantate. As it was a 7x24 non stop system, there was no down-time allowable.
 
At that time I used this method, and voilá!, as soon as a class gets activated, the DLL file gets locked by the framework! Confused | :confused: .
 
The only way to avoid this, was a trick I've found!, and here it goes Cool | :cool:
 
Then you need to load the DLL as a binary memory stream, close it, and then load the assembly from the memory stream (which indeed was the DLL) I make some checksum (MD5) to see if it has changed at all and if so, I make all the rest of the magic, calling the Activator of the new classes, killing the former classes (of the disappered-because-update DLL's), and replacing the newly instantiated (and updated) classes just out-of-the-box (from the new DLL assembly, just dropped in)
Blush | :O
To watch the directories I used the FileWatcher class, but take care with multiple threads when you drop a file in a directory, it fires more than once and may be nasty to debug, take a while, try to lock the file (if you can) and wait until you can lock it, only then accept the calling event-thread.
 
Wink | ;) this is what I can share to all from my little experience under .NET and dynamic non-stop thing's
 
Andres H
Pandora's Box
QuestionWhat about security?membermbghtri7 Apr '08 - 4:47 
AnswerRe: What about security?memberDerek Bartram7 Apr '08 - 8:28 
Generaldirections to #5memberBillWoodruff25 Mar '08 - 6:53 
GeneralRe: directions to #5memberDerek Bartram25 Mar '08 - 9:29 
GeneralRe: directions to #5memberBillWoodruff25 Mar '08 - 14:24 
GeneralVote of less than 5memberDerek Bartram24 Mar '08 - 22:40 
QuestionWhat about generics???memberdatenkabel24 Mar '08 - 19:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 24 Mar 2008
Article Copyright 2008 by Derek Bartram
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid