Frage

I'm trying to inject code to an existing assembly compiled for .NET Framework 3.5 using Mono.Cecil

This is the application structure

  • Console Application --> compiled v4.0

    • Library that wraps calls to Mono Cecil --> compiled v3.5
    • Mono Cecil --> compiled v3.5 (nuget version)
  • External assembly to be injected --> compiled v3.5

the new modified assembly has a double reference to the mscorlib 4.0.0.0 and mscorlib 2.0.0.0

I found out that the problem relies here, when I add a dictionary<,> constructor

 const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
        const MethodAttributes methodAttributes =
            MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName;

        var serializableContructor =
            typeof(Dictionary<object, object>).GetConstructor(flags, null, new[]
            {
               typeof (SerializationInfo), typeof (StreamingContext)
            }, null);


        var serializationConstr = new MethodDefinition(".ctor", methodAttributes, @this.Module.Import(typeof(void)));
        serializationConstr.Parameters.Add(new ParameterDefinition(@this.Module.Import(typeof(SerializationInfo))));
        serializationConstr.Parameters.Add(new ParameterDefinition(@this.Module.Import(typeof(StreamingContext))));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_2));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Call, @this.Module.Import(serializableContructor)));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Nop));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Nop));
        serializationConstr.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
        @this.Methods.Add(serializationConstr);

typeof(Dictionary<,>) return a type that has a reference to the mscorlib 4.0.0.0

what am I doing wrong?

War es hilfreich?

Lösung

If you're using the runtime type system, Cecil will create a reference to the current version you're referencing. In that case, the .net 4.0 Dictionary.

If you want to decouple this, you have to use the Cecil type system to load the proper assembly and create reference for your module.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top