- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
Good morning,
We have been trying to create a class dynamically with IExternalCommand implemented in order to give the new class different names at runtime but still execute our desired method. Our code is:
var ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(nombreassembly), AssemblyBuilderAccess.Run);
var mb = ab.DefineDynamicModule(nombreassembly);
var tb = mb.DefineType(nombreassembly);
tb.AddInterfaceImplementation(typeof(IExternalCommand));
foreach (var imethod in typeof(IExternalCommand).GetMethods())
{
var valueString = ((DescriptionAttribute)imethod.GetCustomAttribute(typeof(DescriptionAttribute))).Description;
var method =
tb.DefineMethod
(
"@@" + imethod.Name,
MethodAttributes.Private | MethodAttributes.Static,
imethod.ReturnType,
new[] { tb }
);
var thisParameter = Expression.Parameter(typeof(IExternalCommand), "this");
var bodyExpression =
Expression.Lambda
(
Expression.Constant
(
Convert.ChangeType(valueString, imethod.ReturnType)
),
thisParameter
);
bodyExpression.CompileToMethod(method);
var stub =
tb.DefineMethod(imethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, imethod.ReturnType, new Type[0]);
var il = stub.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Call, method, null);
il.Emit(OpCodes.Ret);
tb.DefineMethodOverride(stub, imethod);
}
var fooType = tb.CreateType();
var ifoo = (IExternalCommand)Activator.CreateInstance(fooType);
We managed to get the methods within the interface using ifoo at the end, but we have two issues:
- We don´t know how to edit the Execute method within the interface after implementation to add our code to that method.
- We have a line throwing one issue when debugging. This line is: var valueString = ((DescriptionAttribute)imethod.GetCustomAttribute(typeof(DescriptionAttribute))).Description;
The error is: System.NullReferenceException: 'Object reference not set to an instance of an object.' Not sure which type should be set up in this case.
We would really appreciate you help into this.
Thank you
Solved! Go to Solution.
Developer Advocacy and Support +