I want to generate types through reflection at runtime that reference each other.
With static code, I would do this
public class Order
{
public int Id { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int Id { get; set; }
public Order Order { get; set; }
}
I can successfully create my Order and my OrderDetails Type with value type properties.
The code looks like this:
var aName = new System.Reflection.AssemblyName("DynamicAssembly");
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
aName, System.Reflection.Emit.AssemblyBuilderAccess.Run);
var mb = ab.DefineDynamicModule(aName.Name);
var tb = mb.DefineType("Order",
System.Reflection.TypeAttributes.Public, typeof(Object));
var pbId = tb.DefineProperty("Id", PropertyAttributes.None, typeof(int), null);
Now I am stuck on this line:
var pbCustomer = tb.DefineProperty("Customer", PropertyAttributes.None, ???, null);
I need to pass the property type to the DefineProperty method, but the type does not currently exist. Now I could just create a type builder for the client at this moment and use it tb.CreateType()to get the type, but that will not help, because the client also needs a link to the order.
source
share