我甚至不确定这是否可行。在一个方法中,我正在创建一个动态程序集,定义一个类型,并为该类型的构造函数发出IL。此方法将IEnumerable<Action>
作为参数,我希望能够在我生成的类中使用该引用。
我已经编写了一些数据库迁移帮助程序来使用FluentMigrator或MigratorDotNet,我正在尝试实现单元测试以验证功能是否正确。使用FluentMigrator,我可以实例化一个运行器并传递它的Migration类实例。但是,对于MigratorDotNet,它要求我传递一个程序集,它扫描Migration类以实例化并运行 - 因此动态生成。
这是我动态子类化的基类:
public class ActionMigration : Migration
{
private readonly IEnumerable<Action<Migration>> _up;
private readonly IEnumerable<Action<Migration>> _down;
public ActionMigration(Action<Migration> migration) : this(migration, migration) { }
public ActionMigration(Action<Migration> up, Action<Migration> down) : this(new[] { up }, new[] { down }) { }
public ActionMigration(IEnumerable<Action<Migration>> actions) : this(actions, actions) { }
public ActionMigration(IEnumerable<Action<Migration>> up, IEnumerable<Action<Migration>> down) { _up = up; _down = down; }
public override void Down() => _down?.ForEach(m => m(this));
public override void Up() => _up?.ForEach(m => m(this));
}
这是我生成动态实现的代码:
private Assembly BuildMigrationAssembly(IEnumerable<Action<Migration>> actions)
{
var assemblyName = $"mdn_test_{Guid.NewGuid()}";
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyBuilder.GetName().Name, assemblyName + ".dll");
BuildMigrationClass(moduleBuilder, 1, actions);
return assemblyBuilder;
}
private void BuildMigrationClass(ModuleBuilder moduleBuilder, long version, IEnumerable<Action<Migration>> actions)
{
var baseType = typeof(ActionMigration);
var typeBuilder = moduleBuilder.DefineType($"Migration{version}",
TypeAttributes.Public | TypeAttributes.Class |
TypeAttributes.AutoClass | TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
baseType);
var migAttrType = typeof(MigrationAttribute);
var migAttrCtor = migAttrType.GetConstructor(new[] { typeof(long) });
typeBuilder.SetCustomAttribute(migAttrCtor, BitConverter.GetBytes(version));
var baseCtor = baseType.GetConstructor(new[] { typeof(IEnumerable<Action<Migration>>) });
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
var ilg = ctor.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
// how can I pass the local 'actions' object to the base constructor here?
ilg.Emit(OpCodes.Call, baseCtor);
ilg.Emit(OpCodes.Nop);
ilg.Emit(OpCodes.Nop);
ilg.Emit(OpCodes.Ret);
}
我打开了一个项目并创建了一些样本子类来检查:
namespace MdnTest
{
[Migration(1)]
public class Migration1 : EasyMigrator.Tests.Integration.Migrators.MigratorDotNet.ActionMigration
{
public Migration1() : base(new List<Action<Migration>>()) { }
}
}
或者:
namespace MdnTest
{
[Migration(1)]
public class Migration1 : EasyMigrator.Tests.Integration.Migrators.MigratorDotNet.ActionMigration
{
static private readonly IEnumerable<Action<Migration>> _actions;
public Migration1() : base(_actions) { }
}
}
这是他们产生的IL:
.class public auto ansi beforefieldinit
MdnTest.Migration1
extends [EasyMigrator.Tests]EasyMigrator.Tests.Integration.Migrators.MigratorDotNet/ActionMigration
{
.custom instance void [Migrator.Framework]Migrator.Framework.MigrationAttribute::.ctor(int64)
= (01 00 01 00 00 00 00 00 00 00 00 00 ) // ............
// int64(1) // 0x0000000000000001
.method public hidebysig specialname rtspecialname instance void
.ctor() cil managed
{
.maxstack 8
// [14 31 - 14 66]
IL_0000: ldarg.0 // this
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action`1<class [Migrator.Framework]Migrator.Framework.Migration>>::.ctor()
IL_0006: call instance void [EasyMigrator.Tests]EasyMigrator.Tests.Integration.Migrators.MigratorDotNet/ActionMigration::.ctor(class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Action`1<class [Migrator.Framework]Migrator.Framework.Migration>>)
IL_000b: nop
// [14 67 - 14 68]
IL_000c: nop
// [14 69 - 14 70]
IL_000d: ret
} // end of method Migration1::.ctor
} // end of class MdnTest.Migration1
或者:
.class public auto ansi beforefieldinit
MdnTest.Migration1
extends [EasyMigrator.Tests]EasyMigrator.Tests.Integration.Migrators.MigratorDotNet/ActionMigration
{
.custom instance void [Migrator.Framework]Migrator.Framework.MigrationAttribute::.ctor(int64)
= (01 00 01 00 00 00 00 00 00 00 00 00 ) // ............
// int64(1) // 0x0000000000000001
.field private static initonly class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Action`1<class [Migrator.Framework]Migrator.Framework.Migration>> _actions
.method public hidebysig specialname rtspecialname instance void
.ctor() cil managed
{
.maxstack 8
// [15 31 - 15 45]
IL_0000: ldarg.0 // this
IL_0001: ldsfld class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Action`1<class [Migrator.Framework]Migrator.Framework.Migration>> MdnTest.Migration1::_actions
IL_0006: call instance void [EasyMigrator.Tests]EasyMigrator.Tests.Integration.Migrators.MigratorDotNet/ActionMigration::.ctor(class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Action`1<class [Migrator.Framework]Migrator.Framework.Migration>>)
IL_000b: nop
// [15 46 - 15 47]
IL_000c: nop
// [15 48 - 15 49]
IL_000d: ret
} // end of method Migration1::.ctor
} // end of class MdnTest.Migration1
我不确定如何使其适应我想要实现的目标。我可以在IL加载指令中仅仅引用存在于动态程序集上下文之外的本地对象吗?表达式有帮助吗?也许尝试在构造函数中传递它是错误的方法 - 可能改为覆盖上下实现(我可以得到一个函数句柄到一个Action并发出一个调用它,而不是传递给它的引用IEnumerable?)。
我对装配和IL非常熟悉,在审查了操作后,我开始认为我可能无法做我想做的事。
那么,这是否有可能,如果有的话,有人会朝着正确的方向推动我吗?
好奇的是,完整的代码是here。
答案 0 :(得分:0)
您可以通过为动态类定义类型为IEnumerable<Action<Migration>>
的参数的构造函数来路径引用存在于动态程序集之外的对象:
var ctor = typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
new[] { typeof(IEnumerable<Action<Migration>>) });
然后使用这些参数在基类构造函数中对其进行路径:
var ilg = ctor.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0); // load 'this' onto stack
ilg.Emit(OpCodes.Ldarg_1); // load constructor argument onto the stack
ilg.Emit(OpCodes.Call, baseCtor); // call base constructor
ilg.Emit(OpCodes.Ret);
在此之后,您将能够使用Activator
:
var type = typeBuilder.CreateType();
var args = new object[] { new List<Action<Migration>>() };
var instance = Activator.CreateInstance(type, args);