mercredi 17 mars 2021

.NET5: Reading custom attributes of an assembly referencing AspNetCore.MVC

I've written a function to read assembly's custom attributes:

let getAttributes(assemblyPath: string) =
    let assembly = System.Reflection.Assembly.LoadFrom assemblyPath
    assembly.GetCustomAttributes() // <---

It works pretty well, as long as I don't try to load my project which references "Microsoft.AspNetCore.Mvc.Core". Then I get an exception from the line marked by // <---.

Could not load file or assembly "Microsoft.AspNetCore.Mvc.Core, Version=5.0.0.0, ...". The system can't find the file specified.

I though that it might have trouble finding the right location, so I provided a ResolveEventHandler:

let resolveEventHandler =
    ResolveEventHandler(fun _ args ->
        if(args.Name.StartsWith "Microsoft.AspNetCore.Mvc.Core") then
            System.Reflection.Assembly.LoadFrom """C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\5.0.0\ref\net5.0\Microsoft.AspNetCore.Mvc.dll"""
        else
            null

AppDomain.CurrentDomain.add_AssemblyResolve resolveEventHandler

But this brings another exception:

Reference assemblies shall not be loaded for execution. They can only be loaded in Reflection-only context.

I tried switching to Assembly.ReflectionOnlyLoadFrom, but that didn't help, as the operation is said not to be possible on my platform.

So... am I missing anything? Is there any better way of fetching Assembly Attributes without going that much into details?





Aucun commentaire:

Enregistrer un commentaire