Search code examples
c#exceptionmonomono.cecilfody

"Member 'HttpClient' is declared in another module and needs to be imported" in Mono.Cecil / Fody


and thanks for giving me your time.

Background

I'm trying to create a new HttpClient in Mono.Cecil, and to add it to a field. Here's my code:

TypeDefinition HttpClientDef = ModuleDefinition.GetType(typeof(HttpClient)).Resolve();
TypeDefinition def = GetSomeTypeDefinitionFromModule();

FieldDefinition field = new FieldDefinition($"${GENERATED_CLIENT_PATH}", FieldAttributes.Private, HttpClientDef);
def.Fields.Add(field);

No problem here, but once void Execute() has returned, an exception is thrown: Member 'System.Net.Http.HttpClient' is declared in another module and needs to be imported.

So what?

I cannot import HttpClient. I've tried many things, and here's what I know:

  • ModuleDefinition doesn't have a definition for System.Uri or System.Net.Http.HttpClient, for example.
  • I can, however, get a reference to HttpClient by doing:

    AssemblyDefinition httpAssembly = AssemblyResolver.Resolve("System.Net.Http");
    TypeDefinition HttpClientDef = httpAssembly.MainModule.GetType(typeof(HttpClient)); // fyi, HttpClient is also in httpAssembly.GetTypes().
    
  • Once I have a valid TypeDefinition, I have no idea what to do with it.

    • ModuleDefinition.Import(def).Resolve() does not change anything ;
    • new TypeReference(namespace, name, ModuleDefinition, httpAssembly.Name) doesn't work either ;
    • Neither does calling def directly.

Any idea?

Thank you,
Greg.


Edit 1

Turns out you can't import a type if its reference (in this case System.Net.Http) isn't used in the code.
Now, I can load it using TypeDefinition def = ModuleDefinition.GetType(typeof(HttpClient)).


Solution

  • For some reason, System and System.Net.Http weren't referenced, even though I had added 'em as references. Explicitly using HttpClient once in my (modified) code forced the reference to exist, and I was able to Import it after that.