Embed one dll inside another as an embedded resource

Unknown
0
Situation :  When we need to deploy one application which is dependent on other assemblies(dll), and if we forget to attach it to our zip it becomes headache in midnight build time. To overcome this what we can do is embed dll as a resource. Below are the steps to create it.

Step 1
First, add the DLL as Reference

Step 2Then, add the same DLL as file into the project. Right click the project's name > Add > Existing Item...

Step 3
Step 4
Step 5
Now we need to load the DLL from Embedded Resource into Memory for that we will right code when application initializes. We will register a callback method with the AppDomain’s ResolveAssembly event. 

?

  
01
02
03
04
05
06
07
08
09
10
11
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                String resourceName = "ConsoleApplication1." +
                   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);
                }
            };

  
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                String resourceName = "ConsoleApplication1." +
                   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);
                }
            };

Now, the first time a thread calls a method that references a type in a dependent DLL file, theAssemblyResolve event will be raised and the callback code shown above will find the embedded DLL resource desired and load it by calling an overload of Assembly’s Load method that takes a Byte[] as an argument.

Now use functionality(Function or Methods) of this dll as you were using before.














Now build the project and you will see there is only one dll instead of two, actually we embedded that dependent assembly.









Note: You can also use Vitevic assembly loader.



Post a Comment

0Comments

Post a Comment (0)