Sunday, June 08, 2008
« Fixing the Dreaded Error "TF31002: Unabl... | Main | Embedded Resource Assemblies Part II: Wr... »

I've recently developed an application that has the requirement of not having any external dependencies.  That is, the application must, for a variety of reasons, be a stand-alone executable without any bundled libraries or assemblies.  I've already developed some of the functionality that this application relies on, however, and it's packaged in other small utility libraries.  Referencing these assemblies would be the natural decision if I wanted to leverage the functionality.  But that breaks rule #1: no external dependencies.

That aside, I might consider having my project link to the source code files to the other libraries and effectively compile the code directly into my application.  That might, in a simplistic case, be reasonable, but it could easily be unwieldy and unmanagement in the long term.  Not only would I be bringing in classes from another quite distinct namespace into my project, but there's no real tie between them.  A developer may change the source file in a way that breaks my application, introducing other previously-unexpected dependencies.  The list goes on and on as to why this may be a bad idea.

The next thought that came to mind was "What if I were to take the assembly I would otherwise reference and embed it within my application as a resource?  I could load it dynamically at runtime without physically deploying a separate library."  This approach does require a little more work on the part of the developer.

This isn't a new concept.  In fact, several years ago I'd written some code that does this in a similar fashion.  I'm pleased with how effortless it was, however, and I managed to throw this code together in about 20 minutes.

For purposes of the illustration and to test the concept, I created a blank solution in Visual Studio 2008 called 'LoadAssemblyFromResource'.  To this solution, I then added three new projects: EmbeddedAsm (class library), HostAsm (class library), and ClientApp (console application).  EmbeddedAsm is the assembly that will be embedded within HostAsm.  HostAsm represents my application that can't have any external dependencies.  ClientApp is my test harness that will invoke methods on HostAsm.  In turn, HostAsm will leverage the functionality in EmbeddedAsm at runtime.

To set this up, I first created EmbeddedAsm and set the output folder for all configurations to bin\.  Then I and compiled it.  Having functionality within it was not necessary at this point.  Basically, I simply needed to be able to reference the output.  Also, I like having a single target to reference.  This makes the embedding of the assembly easier without having to deal with the bin\Debug or bin\Release directories.

Then, in HostAsm I created a folder called Resources.  I right-clicked that folder and chose 'Add --> Existing Item'.  I then browsed to the bin\ folder of EmbeddedAsm and selected the .dll.  Important: I selected Add As Link rather than Add to add the assembly to the Resources folder.  This enables me to make updates to the EmbeddedAsm and have the HostAsm be updated with the changes.  Were I to have selected Add a copy of the .dll at that point in time would be copied into my Resources folder and any updates to the EmbeddedAsm would be ignored; I'd have to re-add it.

ClientApp has a reference to HostAsm.

The final step in the setup, then, was to right-click on the solution (in the Solution Explorer) and select Project Build Order.  Because HostAsm doesn't actually have a reference to EmbeddedAsm, I had to ensure that it has a dependency on in (on the Dependencies tab).  This forces Visual Studio to compile EmbeddedAsm first so when it gets around to compiling HostAsm it embeds the latest version.

Now for the code...

In EmbeddedAsm I created a very simple class with a simple method:

EmbeddedAsm:

namespace EmbeddedAsm {
   public class CustomClass {
      public string GetMessage() {
         return "Hello from CustomClass";
      }
   }
}

I wrote HostAsm to be a little more robust and reusable.  Rather than simply loading the embedded assembly and running with it, I wanted to put together a bit of a framework (albeit a simple one) to handle the loading of multiple embedded assemblies.

HostAsm:

namespace HostAsm {

   internal static class AssemblyLoader {
      private static Dictionary<string, Assembly> _loadedAssemblies = new Dictionary<string, Assembly>();

      internal static Assembly LoadAssembly(string assemblyName) {
         if ( _loadedAssemblies.ContainsKey(assemblyName) )
            return _loadedAssemblies[assemblyName];

         byte[] bytes;
         using ( Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HostAsm.Resources." + assemblyName) ) {
            bytes = new byte[(int)stream.Length];
            stream.Read(bytes, 0, bytes.Length);
         }

         Assembly asm = Assembly.Load(bytes);
         if ( null == asm )
            throw new ArgumentException("Unable to load assembly: " + assemblyName);

         _loadedAssemblies.Add(assemblyName, asm);
         return asm;
      }


      internal static Type GetType(string assemblyName, string typeName) {
         Assembly asm = LoadAssembly(assemblyName);

         Type type = asm.GetType(typeName);
         if ( null == type )
            throw new ArgumentException(string.Format("Unable to locate type {0} in assembly {1}", typeName, assemblyName));

         return type;
      }
   }

}

The AssemblyLoader class is responsible for the loading of assemblies (naturally) and for retrieving types from the embedded assemblies.  It loads the assemblies by accessing the manifest resource stream of the executing assembly (HostAsm) and fully-qualifying the reference to the embedded library.  Note that the assembly's root namespace is 'HostAsm' and the embedded library is in the Resources folder so the fully-qualified name to the .dll is HostAsm.Resources.EmbeddedAsm.dll.  We then use the Assembly.Load() method to load the assembly from bytes read from the stream.  The assembly is catalogued so we can avoid quickly retrieve an already-loaded library quickly in a subsequent call.  The assembly is then returned to the caller.

The approach I took for accessing and calling the types in the embedded assembly is that of a proxy class.  In this case, the proxy class is coded such that it's methods match those in the class to be called from the embedded assembly.  Also, I wanted to genericize the proxy type so I could, in a repeatable form, invoke methods on other types in a similar fashion.  Therefore, I created a ProxyClassBase type which abstracts away the reflection plumbing necessary to make the calls.  These classes also exist in the HostAsm library.

ProxyClassBase.cs

namespace HostAsm {

   internal abstract class ProxyClassBase {
      protected ProxyClassBase(string assemblyName, string typeName) {
         InstanceType = AssemblyLoader.GetType(assemblyName, typeName);
         Instance = Activator.CreateInstance(InstanceType);
      }

      protected Type InstanceType;
      protected object Instance;

      protected T InvokePublicMethod<T>(string methodName) {
         return (T)InstanceType.GetMethod(methodName).Invoke(Instance, null);
      }
   }

}

CustomClassProxy.cs

namespace HostAsm {

   /// <summary>
   /// Proxy class for EmbeddedAsm.CustomClass.
   /// </summary>

   internal class CustomClass : ProxyClassBase {
      public CustomClass()
         : base("EmbeddedAsm.dll", "EmbeddedAsm.CustomClass") {
      }

      public string GetMessage() {
         return InvokePublicMethod<string>("GetMessage");
      }
   }

}

Note that the CustomClass proxy class invokes the base class's .ctor which in turn uses the functionality in the AssemblyLoader class to encapsulate the creation and management of the type being wrapped.  The method on the CustomClass proxy matches that of the actual CustomClass in EmbeddedAsm except that it defers to the base class's implementation to invoke the method via Reflection.

Then, within my HostAsm I can simply consume the method as though the object were local and participated in the same namespace of my application:

namespace HostAsm {

   public class Worker {
      public void DoWork() {
         CustomClass cc = new CustomClass();
         Console.WriteLine(cc.GetMessage());
      }
   }

}

It's actually quite easy and straightforward.  Not only does this approach help me in my predicament of not being able to support any external dependencies, but I can see how it might be useful in situations where assemblies are packaged and deployed together, used as Add-Ins, etc.  It's pretty cool stuff.

Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, i, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview