How to use a dynamically generated object as the data source of CodeEffects generator

*爱你&永不变心* 提交于 2019-12-05 16:35:33

Extract a portion from the CreateOurNewObject() method that deals with a type creation. Call it CreateType(string xml).

Change the AssemlbyBuilderAccess.Run to AssemblyBuilderAccess.RunAndSave. Then, once the type has been created, call the assemblyBuilder.Save() method. Save it in the location that Assembly.Load will find (e.g. bin or one of .net temp folders), or any other place so long it in the search path.

Use it to create the type and to instantiate objects.

Then, in the index, call

Type myType = CreateType(xml);
RuleModel.Create(myType);

If you are doing evaluation outside make sure to use the same type (don't regenerate it every time). Which means you will need to load it first.

Type myType = Assembly.Load(assemblyName);
object myObject = Activator.CreateInstance(myType);
//...populate myObject with necessary values based on your xml
Evaluator ev = new Evaluator(myType, rule);
bool result = ev.Evaluate(myObject);

or you could use DynamicEvaluator, which simply calls myObject.GetType()

DynamicEvaluator ev = new DynamicEvaluator(rule);
bool result = ev.Evaluate(myObject);

This should work. The important piece here is that you save your assembly first (it cannot be read from the memory at the moment), and that it is in a folder that is part of a search path so that Assembly.Load(name) can find it.

Using your TypeBuilder, you might try tacking on an existing or custom interface to your generated type and then using that as your type.

typeBuilder.AddInterfaceImplementation(typeof(IMyInterface));

Now the object you've created (in the above example) has type IMyInterface, which you could then use in your Index action:

ViewBag.Rule = RuleModel.Create(typeof(IMyInterface));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!