We often need to use external dll’s in CRM plugins which need to be merged into main plugin assembly dll to make it work.
Quoting what ms docs says about using any other dll in your plugin apart from dlls which are part of Microsoft.crmsdk.CoreAssemblies:
Newtonsoft.Json is primary example of such dll’s which is widely used for serialization and deserialization of objects/streams.
Let’s see how we can merge the newtonsoft dll in our plugin assembly so that it works when deployed in a ce environment. (Merging assemblies isn’t officially supported/recommended for CE Plugins, there are alternatives which you can use.)
We have a plugin which uses Newtonsoft dll for deserialization.
Though your project will build successfully even if you don’t do ILMerge since referred Newtonsoft dll lies in packages folder on your machine.
But if you deploy this plugin dll into your CE environment and try to run it, you’ll see similar error as shown below, saying that “Could not load file or assembly “Newtonsoft.json….“
The reason is that you only deployed your plugin dll in CE database but the newtonsoft dll on which your assembly is dependent upon is laying there in your bin folder:-
Now to overcome this problem, we need to et a merged dll which is merger of samplePlugin.dll and Newtonsoft.json.dll.
To do so, follow below steps:-
Step1 :- Install MSBuild.ILMerge.Task from Nuget package manager https://www.nuget.org/packages/MSBuild.ILMerge.Task/
Alternatively you can paste below command in nuget package manager console:
Install-Package MSBuild.ILMerge.Task -Version 1.1.3
Step2 :- Once installed, you’ll see 2 folders created in packages folder of your solution:
a) ILMerge : Which have ILMerge exe application
b) MSBuild.ILMerge.Task : It have the package dll which youn installed.
Step3:- Now set the copy local property of Newtonsoft.json dll to true and set this property to false for all other references.
This ensures that only Newtonsoft.Json dll is mrged with plugin assembly.
Step4:- Now build your solution and you should see only 1 dll (of bigger than usual plugin size since it comprises of both plugin and Newtonsoft dll) in your bin folder as shown below:
Step5:- Now deploy your dll into CE instance.
Step6:- Test the plugin and it should work: