How to define a C # object at runtime?

We have XML code stored in one field of a relational database to get around Entity / Attribute / Value entity problems, however I don't want this to destroy the sunshine of domain modeling, DTO and repository. I cannot get around the EAV / CR content, but I can choose how to save it. The question is, how can I use it?

How can I turn XML metadata into a class / object at runtime in C #?

For instance:

XML will describe that we have a food recipe that has various attributes, but is usually similar, and one or more cooking attributes. The food itself can literally be anything and have any crazy preparation. All attributes are viewable and can link to existing nutritional information.

// <-- [Model validation annotation goes here for MVC2]
public class Pizza {
     public string kind  {get; set;}
     public string shape {get; set;}
     public string city  {get; set;}
     ...
}

and in ActionMethod:

makePizzaActionMethod (Pizza myPizza) {
    if (myPizza.isValid() ) {  // this is probably ModelState.isValid()...
        myRecipeRepository.Save( myPizza);
        return View("Saved");
    }
    else
        return View();
}
+5
3
+9

System.Reflection.Emit .

AssemblyBuilder AppDomain.CurrentDomain

AssemblyBuilder dynAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly("dynamic.dll",
                                                                            AssemblyBuilderAccess.RunAndSave);

ModuleBuilder, TypeBuilder.

AssmblyBuilder .

. , , .

EDIT:

, :

AssemblyName aName = new AssemblyName("dynamic");
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule("dynamic.dll");
TypeBuilder tb = mb.DefineType("Pizza");
//Define your type here based on the info in your xml
Type theType = tb.CreateType();

//instanciate your object
ConstructorInfo ctor = theType.GetConstructor(Type.EmptyTypes);
object inst = ctor.Invoke(new object[]{});

PropertyInfo[] pList = theType.GetProperties(BindingFlags.DeclaredOnly);
//iterate through all the properties of the instance 'inst' of your new Type
foreach(PropertyInfo pi in pList)
    Console.WriteLine(pi.GetValue(inst, null));
+3

: .

I think this is possible with XAML . I would generate a XAML file and then load it dynamically using XamlReader.Load () , creating an object at runtime with the properties I want,

There is an interesting article on XAML as an infrastructure for serializing objects . For more information on the XAML namespace, see here .

+1
source

All Articles