• 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

    • WYSIWYG Web Builder 20.2.1 by Razvan Serea Web Buialder is a WYSIWYG (What-You-See-Is-What-You-Get) program used to create complete web sites. WYSIWYG means that the finished page will display exactly the way it was designed. The program generates HTML (HyperText Markup Language) tags while you point and click on desired functions; you can create a web page without learning HTML. Just drag and drop objects to the page position them "anywhere" you want and when youre finished publish it to your web server (using the build in Publish tool). Web Builder gives you full control over the content and layout of your web pages. One Web Builder project file can hold multiple web pages. Desktop publishing for the web, build web sites as easy as Drag & Drop "One Click Publishing" No FTP program needed. No special hosting required, use with any Hosting Service! Easily create forms using the built-in Form Wizard plus Form validation tools and built-in CAPTCHA. Advanced graphics tools like shapes, textart, rotation, shadows and many other image effects. Fully integrated jQuery UI (Accordion, Tabs etc), animations, effects and built-in ThemeRoller theme editor. Google compatible sitemap generator / PayPal eCommerce Tools Many navigation tools available: Navigation bars, tab menus, dropdown menus, sitetree, slidemenus. Built-in Slide Shows, Photo Galleries, Rollover images, Banners etc. Support for YouTube, Flash Video, Windows Media Player and many other video formats. Unique extension (add-on) system with already more than 250 extensions available! Create HTML5 / CSS3 websites today HTML5 document type (optimized HTML5 output). HTML5 audio/video and YouTube HTML5 support. HTML5 forms: native form validation, new input types and options, web storage. HTML5 canvas and svg support in shapes and other drawing tools. CSS3 @font-face. Use non web safe fonts in all modern browsers. CSS3 opacity, border radius, box shadow. CSS3 gradients. Add cool gradient effects using native CSS3 (no images). CSS3 navigation menu. Create awesome menus without using JavaScript or images. CSS3 animations and transitions. Including support for 2D and 3D transforms! Features for advanced users: Login Tools/Page Password Protection. Built-in Content Management System with many plug-ins (guestbook, faq, downloads, photo album etc). Add custom HTML code with the HTML tools. JavaScript Events: Show/hide objects (with animation), timers, move objects, change styles etc. Layers: Sticky layer, Docking layer, Floating layer, Modal layer, Anchored layer, Strechable layer and more! jQuery Theme Manager, create your own themes for the built-in jQuery UI widgets. Style Manager (global styling, H1, H2, H3 etc). Master Frames and Master Objects: reuse common element in your website. and much more! WYSIWYG Web Builder 20.2.1 changelog: Improved: Images in the properties of Photo Gallery, Photo Grid, Photo Collage and Slide Show can now be re-arrange using drag & drop. Improved: Default aspect ratio of HTML5 audio Fixed: Issue with list item icon offset in workspace. Fixed: 'Edit' button text in Login Admin cannot be changed. Fixed: Issue with Card max-width size calculation in breakpoints Fixed: Issue with (fixed) Layout Grid column height in breakpoints. Download: WYSIWYG Web Builder 64-bit | 30.1 MB (Shareware) Download: WYSIWYG Web Builder 32-bit | 28.0 MB Screenshot: >> Click here << Link: Home Page | Templates | Free extras/addons | Changelog Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Damn no doubt this is gonna be good, can't think of many franchises as consistent as RE (apart from 3 remake)
    • There are two version of qbittorrent 5.1.0 The normal version which I think is based of QT5 & the QT6 lt20 version. I'm currently using the QT6 LT20 version of 5.1.0 and it downloaded an ubuntu iso perfectly fine.
    • Are we forgetting the hardware degradation on 13th and 14th gen??
    • Cry more. The Ukrainians who had internet access because of Starlink were trash too, huh?
  • Recent Achievements

    • One Year In
      Vladimir Migunov earned a badge
      One Year In
    • One Month Later
      daelos earned a badge
      One Month Later
    • Week One Done
      daelos earned a badge
      Week One Done
    • Mentor
      Karlston went up a rank
      Mentor
    • One Month Later
      EdwardFranciscoVilla earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      494
    2. 2
      snowy owl
      252
    3. 3
      +FloatingFatMan
      250
    4. 4
      ATLien_0
      225
    5. 5
      +Edouard
      181
  • Tell a friend

    Love Neowin? Tell a friend!