Home > Net >  Alternative to Assembly.ReflectionOnlyLoad() and ReflectionOnlyLoadFrom()?
Alternative to Assembly.ReflectionOnlyLoad() and ReflectionOnlyLoadFrom()?

Time:06-25

I'm migrating a .Net 4.x application to .Net 6, but the above methods are now deprecated and throw an exception if called. What are the alternatives?

This is the code, which gets passed a list of assembly filenames, and loads any assemblies found to have a certain assembly-level attribute in AssemblyInfo.cs:

AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve  =
    (s, e) => Assembly.ReflectionOnlyLoad(e.Name);

foreach (var assemblyFile in assemblyFilenames)
{
    var reflectionOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile);
    if (FoundOurCustomAttr(reflectionOnlyAssembly))
    {
        var assembly = Assembly.LoadFrom(assemblyFile);
        ProcessAssembly(assembly);
    }
}

CodePudding user response:

Could maybe the methods Assembly.Load and Assembly.LoadFrom be a valid option?

CodePudding user response:

An alternative is using MetadataLoadContext package.

var paths = new List<string>(Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll"));
paths.AddRange(assemblyFilenames);

var resolver = new PathAssemblyResolver(paths);
var ctx = new MetadataLoadContext(resolver);
foreach (var assemblyFile in assemblyFilenames)
{
    var assembly = ctx.LoadFromAssemblyPath(assemblyFile);
    foreach(var a in assembly.CustomAttributes)
        // a.AttributeType
}
  • Related