2012-04-09 16 views
9

Mam następujące klasy:dynamiczne tworzenie Type z konstruktor odwoływać jego zależności

public class Entity<T> where T : Entity<T> { 
    public Factory<T> Factory { get; private set; } 
    public Entity(Factory<T> factory) { 
     Factory = factory; 
    } 
} 
public class Factory<T> { } 

public class MyEntity : Entity<MyEntity> { 
    public MyEntity(Factory<MyEntity> factory) : base(factory) { } 
} 

Próbuję dynamicznie utworzyć klasy MyEntity z konstruktora określony. Do tej pory mam następujący kod:

class Program { 
    static ModuleBuilder _moduleBuilder; 
    public static ModuleBuilder ModuleBuilder { 
     get { 
      if (_moduleBuilder == null) { 
       AssemblyBuilder asmBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(new AssemblyName("Dynamic"), AssemblyBuilderAccess.Run); 
       _moduleBuilder = asmBuilder.DefineDynamicModule("MainModule"); 
      } 
      return _moduleBuilder; 
     } 
    } 

    static void Main(string[] args) { 
     TypeBuilder typeBuilder = ModuleBuilder.DefineType("MyEntity", TypeAttributes.Public); 
     Type baseType = typeof(Entity<>).MakeGenericType(typeBuilder); 
     typeBuilder.SetParent(baseType); 

     Type factoryType = typeof(Factory<>).MakeGenericType(typeBuilder); 


     ConstructorBuilder cBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { factoryType }); 
     ILGenerator ctorIL = cBuilder.GetILGenerator(); 
     ctorIL.Emit(OpCodes.Ldarg_0); 
     ctorIL.Emit(OpCodes.Ldarg_1); 
     ConstructorInfo c = baseType.GetConstructor(new Type[] { factoryType }); 
     ctorIL.Emit(OpCodes.Call, c); 
     ctorIL.Emit(OpCodes.Ret); 

     Type syType = typeBuilder.CreateType(); 
     Console.ReadLine(); 
    } 
} 

Kod nie powiódł się @ConstructorInfo c = baseType.GetConstructor(new Type[] { factoryType }). Dostałem wyjątek NotSupportedException.

Czy jest jakiś sposób, aby to osiągnąć? Od trzech dni jestem odtrącany. Każda pomoc będzie doceniona.

Dzięki!

+1

Dzwonisz do Eric Lippert, Eric Lippert? – Joe

+2

@JoeTuskan: Nie sądzę, że jestem tu potrzebny; jest to proste pytanie dotyczące refleksji. –

Odpowiedz

3

Musisz użyć metody statycznej TypeBuilder.GetConstructor. Myślę, że to powinno działać (nietestowane):

ConstructorInfo genCtor = typeof(Entity<>).GetConstructor(new Type[] { typeof(Factory<>).MakeGenericType(typeof(Entity<>).GetGenericArguments()) }); 
ConstructorInfo c = TypeBuilder.GetConstructor(baseType, genCtor); 
Powiązane problemy