Dynamics CRM 2011 Plugin With Custom Referenced Libraries

By | March 19, 2012

It is not possible to deploy referenced libraries with the assembly which contains the crm plugins. You can install the libraries into the GAC, but it isn’t really a good solution. Two weeks ago, I found a cool solution in the internet about embedding referenced assemblies into one library or exe. I implemented this code in my crm plugin project.


Here is my plugin project with 5 referenced libraries. Inside the project I created a folder “_Resource” and defined a pre-build event, which copies the compiled referenced libraries into this folder. Then I set the “build action” to “embedded resource”.


Embedded Libraries

Embedded Libraries

With this pre-build event the IDE copies the dlls into the resource folder. (Example with the business dll)

copy $(ProjectDir)..\MyProject.Business\$(OutDir)\MyProject.Business.dll $(ProjectDir)_Resource /Y

After compiling the solution, the referenced assembly are embedded inside the plugin dll.
Here is a picture of the compiled dll.

Embedded Libraries in DLL

Embedded Libraries in DLL


Now we need custom code, which loads the embedded dll at runtime.

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
    var resourceName = AssemblyLoader.ResourceName + new AssemblyName(args.Name).Name + ".dll";

    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        Byte[] assemblyData = new Byte[stream.Length];
        stream.Read(assemblyData, 0, assemblyData.Length);
        return Assembly.Load(assemblyData);

The runtime raises the “AssemblyResolve” event when the the resolution of an assembly fails.
The code above loads the assembly out of the resources and returns it to the runtime.
This is it! Now you can split your code in 100 assemblies (like in every good designed application 😉 ) and merge them into one file.


There are other solutions like “ILMerge”. But the above described solution is the most suitable, because you don’t need extra tools.