15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

if (!File.Exists (path)) return null; // Sanity check<br />

return Assembly.LoadFrom (path); // Load it up!<br />

}<br />

}<br />

class Program<br />

{<br />

internal static void Go()<br />

{<br />

// Now we can reference types defined in c:\ExtraAssemblies<br />

}<br />

}<br />

It’s vitally important in this example not to reference types in<br />

c:\ExtraAssemblies directly from the Loader class (e.g., as fields),<br />

because the CLR would then attempt to resolve the type before<br />

hitting Main().<br />

In this example, we could use either LoadFrom or LoadFile. In either case, the CLR<br />

verifies that the assembly that we hand it has the exact identity it requested. This<br />

maintains the integrity of strongly named references.<br />

In Chapter 24, we describe another approach that can be used when creating new<br />

application domains. This involves setting the application domain’s PrivateBin<br />

Path to include the directories containing the additional assemblies—extending the<br />

standard assembly probing locations. A limitation of this is that the additional directories<br />

must all be below the application base directory.<br />

Packing a Single-File Executable<br />

Suppose you’ve written an application comprising 10 assemblies: 1 main executable<br />

file, plus 9 DLLs. Although such granularity can be great for design and debugging,<br />

it’s also good to be able to pack the whole thing into a single “click and run”<br />

executable—without demanding the user perform some setup or file extraction ritual.<br />

You can accomplish this by including the compiled assembly DLLs in the main<br />

executable project as embedded resources, and then writing an AssemblyResolve<br />

event handler to load their binary images on demand. Here’s how it’s done:<br />

using System;<br />

using System.IO;<br />

using System.Reflection;<br />

using System.Collections.Generic;<br />

public class Loader<br />

{<br />

static Dictionary _libs<br />

= new Dictionary ();<br />

static void Main()<br />

{<br />

676 | Chapter 17: Assemblies

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!