how to selectively load .NET libraries

I am writing an application that will be able to work with different types of hardware. Each type of hardware comes with a different .NET library that is used to communicate with the hardware. My application will only use one type of hardware at any given time.

My application will be installed on different computers and only one type of hardware will be installed in a computer. As such, it should only be necessary to install the driver library that is associated with that particular type of hardware.

When the user runs my application, he will select the type of hardware that is installed in the computer. I then want my application to selectively load only the hardware library that it needs.

My question is as follows. Is there a way in .NET that my application can selectively load only those libaries that it needs at run time

I am just starting to work with C++/CLI and C# in VS2005 Pro.

Thanks,

Ian



Answer this question

how to selectively load .NET libraries

  • GMS0012

    Actually it's rather simple if you can factor your device support to a common interface. Here's an example of using reflection/configuration to load only the appropriate type into memory.

    // Get the typename using your favorite method (e.g. read from registry, config file etc.)

    string typeName = ConfigurationManager.AppSettings["DeviceSupportType"];
    IDeviceSupport device ;
    if (!string.IsNullOrEmpty(typeName))
    {
    Type deviceSupportType = Type.GetType(typeName, true);

    // This assumes that you will leverage the default ctor, if your ctor requires parameters then you'll have to modify these next two calls a bit to get the right ctor and invoke it properly
    ConstructorInfo ci = deviceSupportType.GetConstructor(Type.EmptyTypes);
    device = ci.Invoke(null) as IDeviceSupport;
    if (device == null)
    throw new InvalidCastException("Unable to find appropriate device support class.");
    }
    else
    {
    throw new InvalidCastException("Unable to find appropriate device support class.");
    }


  • KitGreen

    Yes, but it's a little bit tricky. You can use the System.Reflection.Assembly class to dynamically load .NET DLL files. You can then access the objects inside using Reflection.

    If the libraries are small, there's little harm in merging them (or just loading all of them) so the types are visible at compile time, to avoid reflection hassles. The .NET JIT does't compile methods you don't use, so the memory impact would be minimal.

    -Ryan / Kardax


  • how to selectively load .NET libraries