• 0

C# Better & more efficient way to load DLL dynamically & get interf


Question

Hi,

Been using the code below to load a dll dynamically and get an instance of certain interface. This was done way back in .NET 2 days. What is a better & more efficient way to do this using .NET 4 functionality?


// Usage
ICountryHandler pCountryHandler = GetInstanceFromModule<ICountryHandler>("Company.Product.Country.Australia.dll");

public static TInterface GetInstanceFromModule<TInterface>(string AModuleName)
where TInterface : class
{
Assembly pAssembly;
ConstructorInfo pConstructor;
TInterface pInstance;
Type pInterface;
pAssembly = null;
if (AModuleName.Contains(Path.DirectorySeparatorChar.ToString()) || AModuleName.Contains(Path.AltDirectorySeparatorChar.ToString()) || AModuleName.Contains(Path.PathSeparator.ToString()) || AModuleName.Contains(Path.VolumeSeparatorChar.ToString()))
{
pAssembly = Assembly.LoadFrom(AModuleName);
}
else
{
pAssembly = Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), AModuleName));
}
if (pAssembly != null)
{
foreach (Type pType in pAssembly.GetExportedTypes())
{
pInterface = pType.GetInterface(typeof(TInterface).ToString());
if (pInterface != null)
{
pConstructor = pType.GetConstructor(new Type[] { });
pInstance = pConstructor.Invoke(null) as TInterface;
if (pInstance != null)
{
return pInstance;
}
}
}
}
return null;
}
[/CODE]

TA :)

10 answers to this question

Recommended Posts

  • 0


pInterface = pType.GetInterface(typeof(TInterface).ToString());
if (pInterface != null)[/CODE]

I take it this tests if pType implements TInterface? I'd do:

[CODE]if (typeof(TInterface).IsAssignableFrom(pType))[/CODE]

Also rather than getting the default constructor and invoking explicitely, you could use Activator for that:

[CODE]
pConstructor = pType.GetConstructor(new Type[] { });
pInstance = pConstructor.Invoke(null) as TInterface;

// instead do
pInstance = (TInterface)Activator.CreateInstance(pType);[/CODE]

No need to use [font=courier new,courier,monospace]as[/font] and check for null since you just checked that pType implements TInterface: the cast must necessarily succeed.

None of this is .NET 4-specific but might allow you to cut down the number of lines a bit.

  • 0

You should divide that method into smaller methods - one to get the assembly from a string, one to get all types implementing an interface, and one to create an instance of all these types.

Your check for absolute path can be replaced with Path.IsPathRooted().

Also, stop using Hungarian notation...especially if you're not actually using the prefix but just using "p" at the beginning of everything. It's both ugly and useless. ( see http://msdn.microsoft.com/en-us/library/vstudio/ms229045.aspx - "Do not use Hungarian notation").

  • 0

Actually the biggest efficiency gains here would be by caching the results. Iterating all the types in an assembly can take a long time and you're doing it every time the method is called. Of course, measure your gains - how much time this method currently takes and how much you're saving (or wasting!) by doing things differently. You might find out this method takes an insignificant amount of time and you're just worrying for nothing.

  • Like 1
  • 0
  On 04/10/2012 at 07:58, Dr_Asik said:

Iterating all the types in an assembly can take a long time and you're doing it every time the method is called.

(Y)

Unless it's a once-off thing - then it's probably not worth overcomplicating it.

And just for fun, here's a LINQ version:

(PS: If you often need to test code snippets (not necessarily LINQ-related), LINQPad is invaluable)


public static TInterface GetInstanceFromModule<TInterface>() where TInterface : class
{
// Change this to load assembly from file
var pAssembly = Assembly.GetAssembly(typeof(TInterface));

// Magic!
if (pAssembly != null)
return pAssembly.GetExportedTypes()
.Where(t => t.IsClass)
.Where(t => typeof(TInterface).IsAssignableFrom(t))
.Select(t => (TInterface)Activator.CreateInstance(t))
.FirstOrDefault();

return null;
}
[/CODE]

Edit: It doesn't really increase efficiency, but does make it a lot easier on the eyes. And [i]slightly[/i] harder to debug :p

Edited by GreenMartian
  • 0

Thanks guys.

I am using hungarian notations as that is the coding practices where I work and I gotta follow their guidelines. I am going to implement few of these suggestions and see how things go. I am only calling this once for each DLL that I want to load and once they are loaded that is it.

I read somewhere to use newly introduced dynamic key word and use managed extensibility framework but I am stuck there... Any advice on that would be useful too.

Cheers :)

  • 0

Ah, didn't realise MEF is now built into .NET 4.

From your example, it looks like you're looking more into Dependency Injection (DI). From what I remember, MEF does it to some extent, but is more geared towards supporting extensions (I haven't actually used it, but did some reading on it a couple years ago, so feel free to correct me).

There are multiple frameworks that provide DI Containers. Personally, I've only used Castle Windsor. There's also Unity, and a few others.

Setup properly, DI containers make it ridiculously easy to inject interface implementations to other classes.

In a nutshell, you basically tell it once, at the start of your app, to load a config from an xml file like so:

container.Install(Configuration.FromXmlFile("settings.xml")

With the xml file looking something like

&lt;configuration&gt;
&lt;components&gt;
  &lt;component service="Namespace.ICountryHandler, AssemblyNameOfInterface"
	type="Namespace.AustralianHandler, AssemblyNameOfImplementor" /&gt;
&lt;/components&gt;
&lt;/configuration&gt;

And everywhere else in the code when you have a property of type ICountryHandler, you'll get the Australian handler.

PS: Thanks for mentioning MEF. I might revisit it and see what MS have been up to. There goes my weekend!

This topic is now closed to further replies.
  • Posts

    • Or, it is Apple simply overinflated the screens.
    • Is it that easy though? WhatsApp is the default way the majority message in a lot of countries these days. I would prefer Signal to be as popular as WhatsApp and probably could get a few people to use it, most people are probably going to stick with WhatsApp sadly. Which leaves SMS or Facebook Messenger as alternatives a lot of people also have. (Here anyway, I know iMessage, LINE and WeChat dominate in certain parts of the world). It annoying Meta purchased WhatsApp all those years ago.
    • Do they tell Google not to scrape their content via something like robots.txt? Do they specify anywhere that certain agents aren't to scrape? If not, tough. Plus there's no obligation on anyone's part to adhere to any directives that might be in this file anyway...
    • DMDE 4.3.5.823 Beta by Razvan Serea DMDE is a software designed to effectively recover lost data. It retrieves files and folders swiftly and stores them in the user-defined location. It is an easy to use yet powerful tool that will assist both novice and experienced users in getting back lost files in just a few simple steps. Free Edition includes all basic features but a single recovery operation recovers up to 4000 files in the current panel only (you should first open a subdirectory in the current panel and then recover files in the panel). In paid licenses there is no this restriction, and recovery of nested directories is allowed. Can paid versions recover more files than the free version of DMDE? If a file cannot be recovered in the DMDE Free Edition (or it is damaged after recovery) the same will occur in the paid versions. DMDE paid versions are capable of recovering the same files. The only difference is that paid versions can recover all found files in one go, as well as restore the directory structure presented in the free version. Professional Edition provides additional features: rights to provide data recovery services portable use on different computers one-time activation on client computers (including remote use) data recovery reports (include logs and file checksums) read support for E01 disk image files using logs when copying a disk (resume copying, multiple passes) customizable I/O handler script recovery of NTFS alternate data streams DMA access in DOS (for ATA interface) DMDE key features: Portable run without installation Support for NTFS, FAT12/16, FAT32, exFAT, ReFS, Ext2/Ext3/Ext4, btrfs, HFS+/HFSX, APFS Thorough FS and Raw scan, FS reconstruction for data recovery in complex cases Simple partition manager for express search, diagnostics, and restoration of partitions Disk cloning and disk image creating, including I/O error handling, reverse copying, and other features RAID constructor for virtual RAID reconstruction supporting levels RAID-0, RAID-1, RAID-4, RAID-5, RAID-6, delayed parity, custom striping, JBOD/spanned disks; automatic calculation of RAID configurations Cluster map to investigate file allocation Disk editor compatible with the most recent Windows versions which allows viewing, editing, and navigating through different disk structures using built-in and custom templates NTFS tools to work bypassing NTFS driver (copy, delete file, create, repair directory) Support for various device I/O interfaces and settings to work with damaged devices, disk images, NTFS compression and encryption, national names, large disks, large files, large sectors, and other features DMDE 4.3.5.823 Beta changelog: Expanded built-in signatures for RAW search functionality Added file list export to HTML format (DMDE Professional Edition only, view sample) Improved handling of I/O errors with selective skipping by error code Enabled preview support for additional image (graphic) file types (Windows only) Improved extfs reconstruction when copies of superblocks with group descriptors are found Fixed potential hang during Btrfs volume reconstruction Resolved issue with cluster list creation when subfolders are present Other improvements and fixes Download: DMDE 64-bit | 2.4 MB (Free, paid upgrade available) Download: DMDE 32-bit | 2.0 MB Link: DMDE Home Page | DMDE Manual | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The BBC might have gone about this the wrong way, but if there is a revenue sharing program then they and all other "providers" of data should be included in the plan.
  • Recent Achievements

    • Week One Done
      Crunchy6 earned a badge
      Week One Done
    • One Month Later
      KynanSEIT earned a badge
      One Month Later
    • One Month Later
      gowtham07 earned a badge
      One Month Later
    • Collaborator
      lethalman went up a rank
      Collaborator
    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      679
    2. 2
      ATLien_0
      276
    3. 3
      Michael Scrip
      220
    4. 4
      +FloatingFatMan
      170
    5. 5
      Steven P.
      164
  • Tell a friend

    Love Neowin? Tell a friend!