Friday, September 22, 2017

Resolving assemblies when using PnP Core and ADAL / Graph

This is a super technical post and it goes like this:


If you use NuGet and reference PnP as well as ADAL and Graph clients as I have above, and you write code to apply a pnp template you might run into DLL hell and get the following exception:

"Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information."

The reason is that PnP take a dependency on both of these libraries, but on older versions. Deep in the code PnP uses reflection to find all serializer types, and it will throw up an assembly loader exception due to you having newer versions of these DLL’s in your project.

You can either align your dependency with what PnP uses, or you add an assembly redirect from the older to newer versions. Below is code which will dynamically resolve to the newest version for these issues.

Note: This assumes your version is newer than whatever PnP takes a dependency on

Add the code in a static constructor, or somewhere else which ensures it runs once for your application.

public static void RedirectAssembly()
    var list = AppDomain.CurrentDomain.GetAssemblies().OrderByDescending(a => a.FullName).Select(a => a.FullName).ToList();
    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
        var requestedAssembly = new AssemblyName(args.Name);
        foreach (string asmName in list)
            if (asmName.StartsWith(requestedAssembly.Name + ","))
                return Assembly.Load(asmName);
        return null;

Funny part is that it now works fine for me without this code – but, just in case :)