dimanche 28 mai 2023

C# Assembly Resolve Context problems

I'm loading an Assembly that references to TPL.DataFlow library and I was having problems because TPL.DataFlow dll was not loading. As I have read in Microsoft Documentation when using Assembly.LoadFrom() the folder of the assembly is taking in consideration in the Assembly Load Context.

I have solved the problem using the AssemblyResolve event but it's extrange that in debugging I have seen that the if (assembly == null) condition is not reached, so the assembly was loaded in context but not resolved.

Even that I have solved the problem I was surprised about that and that is why I'm asking about AssemblyResolve context

public static IService LoadService(CtorParameters parameters)
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
        CurrentDomain_AssemblyResolve(sender, args, parameters.DllLocation);
    try
    {
        var assembly = Assembly.LoadFrom(parameters.DllLocation);
        var serviceType = assembly.GetType(SERVICE_TYPE);
        var serialPortInstance = (IService)Activator.CreateInstance(serviceType, parameters);
        return serialPortInstance;
    }
    finally
    {
        AppDomain.CurrentDomain.AssemblyResolve -= (sender, args) =>
            CurrentDomain_AssemblyResolve(sender, args, parameters.DllLocation);
    }
}

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args, string loadedAssemblyPath)
{
    var appDomain = (AppDomain)sender;
    if (args.RequestingAssembly == null)
    {
        try
        {
            var assemblyName = new AssemblyName(args.Name);
            var assembly = appDomain.GetAssemblies().FirstOrDefault(m => m.GetName().Name == assemblyName.Name);
            if (assembly == null)
            {
                var loadedDllDir = Path.GetDirectoryName(loadedAssemblyPath);
                var dllPath = Path.Combine(loadedDllDir, $"{assemblyName}.dll");
                assembly = Assembly.LoadFrom(dllPath);
            }
            return assembly;
        }
        catch { }        
    }
    return args.RequestingAssembly;
}




Aucun commentaire:

Enregistrer un commentaire