2017-03-08 52 views
1

我甚至不确定这是否可能..在一个方法中,我创建了一个动态程序集,定义了一个类型,并为构造函数发送了IL那种类型。此方法以IEnumerable<Action>作为参数,我希望能够在我生成的类中使用该引用。如何在使用IL动态生成的类中使用本地对象Emit

我已经写了一些数据库迁移助手与FluentMigrator或MigratorDotNet一起工作,我试图实现单元测试来验证正确的功能。借助FluentMigrator,我可以实例化一个跑步者并将其传递给Migration类的实例。但是,使用MigratorDotNet时,它需要我为它传递一个程序集,它会扫描Migration类以实例化并运行 - 因此是动态生成。

这是基本I类动态是子类:

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加载指令中插入一个对动态程序集上下文之外存在的本地对象的引用?表达式可以帮助吗?也许试图在构造函数中传递它是一种错误的方式 - 也许是改写up和down的实现(我可以像一个Action的函数句柄并发出一个调用它,而不是传入参考IEnumerable?)。

我很熟悉程序集和IL,并在审查操作后,我开始认为我可能无法做我想做的事情。

那么,这是甚至可能的,如果有的话,是否有人可以推动我朝着正确的方向发展?

对于好奇,完整的代码是here

+0

不知道这是否让你更接近或没有:http://stackoverflow.com/q/8419839 –

+0

@CALohse它没有。我从来没有找到一种方法来直接发布任何类型的引用到我发布IL时的动作 - 但是工作是将该动作存储在静态字典中,并在动态程序集中发出调用以致电回到一个静态函数中,该静态函数返回动态类的正确动作然后调用。我必须在代码中添加一个答案。 –

回答

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); 
+0

@CALohse上面的评论导致了同样的解决方案。问题是我不控制我动态生成的类的实例化。迁移运行器 - 一个MSBuild目标或exe - 实例化这个类,并且总是寻找一个无参数的构造函数。 –

相关问题