Hi,
I am using Mono.Cecil to inject and move code in some of our
libraries. First, I read the method definitions of all types in the
assembly and then create in C# the code that should be injected. I
build the C# code in a different assembly, and finally start injecting
that code in the original assembly.
The injection algorithm is the following:
foreach (TypeDefinition injectionType in injectionTypesQuery)
{
string injectedTypeName =
injectionType.FullName.Replace(injectionType.Name,
injectionType.Name.Remove(0, "_".Length).Replace('_','/'));
TypeDefinition injectedType =
injectedMainModule.GetType(injectedTypeName);
Mono.Collections.Generic.Collection<MethodDefinition>
injectedMethods = injectedType.Methods;
List<MethodDefinition> injectionMethods = (from injectionMethod in
injectionType.Methods
where !
injectionMethod.IsConstructor
select
injectionMethod).ToList();
foreach (MethodDefinition injectionMethod in injectionMethods)
{
MethodDefinition injectedMethod =
injectedMethods.First(currentMethod =>
AreIdenticalMethods(currentMethod, injectionMethod));
Mono.Cecil.Cil.MethodBody injectedBody = injectionMethod.Body;
Mono.Cecil.Cil.MethodBody originalBody = injectedMethod.Body;
injectionMethod.Name = "~" + injectionMethod.Name;
injectionType.Methods.Remove(injectionMethod);
injectedMethod.Body = injectedBody;
injectionMethod.Body = originalBody;
injectedType.Methods.Add(injectionMethod);
}
}
The idea is first read all methods in the assembly with the injection
code. Then find the corresponding method in the original assembly and
interchange the body of both methods. Finally, I add the method of the
injection assembly (with the method name changed) in the original
assembly.
The problem that I am facing is that the injection code, the code that
comes from the injection assembly, does not work in the original
assembly. After rewriting the original assembly with the changes been
made, if I open the assembly with Reflector I see that type references
are wrong (the assembly does not correspond with the type):
[0] class
[Basoa.Framework.Service]System.Reflection.MethodBase base2,
[1] class
[System.Data.Entity]Microsoft.Practices.EnterpriseLibrary.PolicyInjection.HandlerPipeline
pipeline,
[2] class
[Basoa.Framework.Service]System.Collections.Generic.List`1<class
[System.Data.Entity]Microsoft.Practices.EnterpriseLibrary.PolicyInjection.ICallHandler>
list,
[3] class
[System.Data.Entity]Microsoft.Practices.EnterpriseLibrary.PolicyInjection.IMethodReturn
return2,
Debugging the alogithm I cannot see when I lose the type references,
so I hope that someone could shed me some light in this question. I am
a newbie at IL level and Mono.Cecil, so I apologize if the mistake I
will be making for sure is very silly.
Thanks in advance.
Best regards,
Jose Antonio Arroba
--
--
mono-cecil