给定的规则集不包含System.Object,mscorlib,

时间:2016-06-16 22:57:02

标签: c# .net dynamic reflection codeeffects

首先,我使用www.codeeffects.com框架制作业务规则评估程序,但在我的情况下,我需要100%动态的类型。

我在概念证明方法中有以下代码。

public ActionResult Save(RuleModel ruleEditor)
{
    DummyEntitiesGen gen = new DummyEntitiesGen();
    Type t = gen.CreateType();
    List<dynamic> lista= gen.CreateTypeList();
    // At this point the rule model doesn't know which type to use as its source object
    // We need to "bind" the source type to the rule model
    ruleEditor.BindSource(t);

    // Add the rule model to the ViewBag object
    ViewBag.Rule = ruleEditor;

    // Make sure that the Rule Area is not empty and the current rule is valid
    if (ruleEditor.IsEmpty() || !ruleEditor.IsValid(StorageService.LoadRuleXml))
    {
        ViewBag.Message = "The rule is empty or invalid";
        return View("Index");
    }
    try
    {
        // Save the rule
        StorageService.SaveRule(
            ruleEditor.Id,
            ruleEditor.GetRuleXml(),
            ruleEditor.IsLoadedRuleOfEvalType == null ?
            true : (bool)ruleEditor.IsLoadedRuleOfEvalType);

        // Get all rules for Tool Bar and context menus and save it in the bag
        this.LoadMenuRules();

        DynamicEvaluator evaluator = new DynamicEvaluator(ruleEditor.GetRuleXml());               
        //bool success = evaluator.Evaluate(lista, ruleEditor.Id);

        IEnumerable<dynamic> result = lista.Filter<dynamic>(ruleEditor.GetRuleXml());
        //var result = lista.AsQueryable<t>().Filter(ruleEditor.GetRuleXml());

        ViewBag.Message = "The rule was saved successfully";
    }
    catch (Exception ex)
    {
        ViewBag.Message = ex.Message;
    }
    return View("Index");
}

对象lista很好,并返回一个我在调试时可以看到的动态类型列表。

然而,应该过滤的行给了我这个例外:

给定的规则集不包含System.Object,mscorlib

类型的任何规则

1 个答案:

答案 0 :(得分:2)

GetRuleXml()方法返回一个XML,其中 type 属性设置为源对象的类型。在你的情况下,它将是gen.CreateType()方法返回的类型的名称,例如:

<rule id='03b33dd0-4389-4ac4-a5aa-bd81fab41e00' eval='true' webrule='4.0.0.8' utc='10/20/2011 4:19:27 PM'
type='MyApplication.MyClass, MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ab44223d08cca81e'>

在编译阶段,引擎会根据 type 属性指定的类型检查实例对象的类型。如果它们不匹配,则会得到该异常(&#34;给定的规则集不包含任何规则......&#34;)。

您可以通过清除或删除类型属性来避免此问题。这样做会在编译期间绕过类型检查。

也就是说,CodeEffects规则引擎支持动态对象或类型。还没有。

DynamicEvaluator是一个遗留类,与动态对象或类型无关。它为每种类型的对象构建一个评估者字典,该对象被评估,允许为各种类型重用相同的规则,只要它们的属性和方法匹配。

规则元素中删除类型属性后,您将获得另一个异常,很可能是&#34; System.ArgumentException:&#39; < EM> X &#39;不是#System; Object.Object&#39;&#34;。

类型的成员

这是因为.NET中没有动态类型。 Dynamic只是告诉编译器在编译期间跳过类型检查,并在运行时添加一些魔法。但是,它下面会以Object形式传递。

引擎使用表达式来构建规则,而不是反射。由于在动态情况下它是Object,因此无法找到规则XML中使用的任何属性或方法。

有计划添加对动态对象(实现IDynamicMetaObjectProvider的对象)的支持,但我不知道时间范围。