lundi 24 juillet 2017

.NET: Custom assembly resolution failing when loading resources

I have a project which needs to load extra assemblies dynamically at runtime for reflection purposes. I need custom code because the path to the DLLs is not known by the framework. This code works fine with normal DLLs, they load fine and I can reflect over them. However, when I attempt to load types which statically uses embedded resources (i.e. a resx) this code fails.

Without my custom assembly resolution code this works fine. Here is my assembly resolution code:

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    bool isName;
    string path = GetAssemblyLoadInfo(args, out isName);
    return isName ? Assembly.Load(path) : Assembly.LoadFrom(path);
}

static string GetAssemblyLoadInfo(ResolveEventArgs args, out bool isAssemblyName)
{
    isAssemblyName = false;
    var assemblyName = new AssemblyName(args.Name);
    string path = String.Concat(new FileInfo(DllPath).Directory, "\\", assemblyName.Name, ".dll");
    if (File.Exists(path))
    {
        return path;
    }
    if (path.EndsWith(".resources.dll"))
    {
        path = path.Replace(".resources.dll", ".dll");
        if (File.Exists(path)) return path;
    }

    var assemblyLocation = AssemblyLocations.FirstOrDefault(al => al.Name.FullName == assemblyName.FullName);
    if (null == assemblyLocation)
    {
        isAssemblyName = true;
        return args.Name;
    }
    else
    {
        return assemblyLocation.Location;
    }
}

Here is a link to a project which recreates the entire issue:

http://ift.tt/2ttSP6R

Once you download the project and run it it should work fine and write the string "This is the value of the resource" to the console, which comes from the resx file. However, uncomment line 23 in Program.cs and run it again and it will fail with an exception, which indicates that it failed to load the embedded resources.





Aucun commentaire:

Enregistrer un commentaire