2016-06-16 34 views
3

首先,我使用www.codeeffects.com框架來創建一個業務規則評估器,但在我的情況下,我需要類型爲100%動態。給定的規則集不包含任何類型爲System.Object的規則,mscorlib,

我在我的概念驗證方法中有以下代碼。

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"); 
} 

對象列表很好,並返回一個創建的動態類型列表,我可以在調試時看到它。

但是這應該是高效過濾器是給我這個異常的行:

給定的規則集不包含具有System.Object類型的任何規則,mscorlib中

回答

2

的GetRuleXml()方法返回的XML與將類型的屬性設置爲源對象的類型。在您的情況下,將通過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'> 

在編譯階段的引擎檢查一個實例對象的抵抗由指定的類型鍵入屬性。如果它們不匹配,則會得到該異常(「給定的規則集不包含任何規則...」)。

您可以通過清除或刪除類型屬性來避免它。這樣做會在編譯期間繞過類型檢查。

也就是說,CodeEffects規則引擎確實支持動態對象或類型的而不是。還沒有。

DynamicEvaluator是一個遺留類,它與動態對象或類型無關。它爲評估對象的每種類型構建一個評估程序字典,該評估程序允許重複使用各種類型的相同規則,只要它們的屬性和方法匹配。

一旦刪除從規則元素屬性,你會得到一個不同的異常,最有可能的「System.ArgumentException:‘X’不是類型的成員‘System.Object的’」 。

這是因爲在.NET中沒有這樣的動態類型。動態僅僅告訴編譯器在編譯期間跳過類型檢查,並在運行時增加一些魔力。然而,它下面是作爲對象傳遞。

引擎使用表達式構建規則,而不是反射。由於它是動態的對象,因此它將無法找到規則的XML中使用的任何屬性或方法。

有計劃添加對動態對象(實現IDynamicMetaObjectProvider的對象)的支持,但我不知道時間範圍。