【问题标题】:While rule evaluation Db Connection null exception而规则评估数据库连接空异常
【发布时间】:2020-08-11 07:54:19
【问题描述】:

在评估它初始化类 B 并调用默认构造函数的规则时,我陷入了一个场景,但我正在通过参数构造函数注入 Db 连接。请参阅下面的代码和建议。

public class A
{
    [ExternalMethod(typeof(B), "IsSpecialWord")]

    [Field(DisplayName = "English Word", Description = "English Word", Max = 200)]
    public string EngWord { get; set; }
}

public class B
{
    public IDbCoonection dbCon { get; set; }
    public B(IDbConnection db)
    {
        dbCon = db;
    }

    [Method("Is Special Word", "Indicates to test abbreviated word")]
    public IsSpecialWord(sting word)
    {
        db.CheckSpecialWord(word);
    }

    public insert SpecialWord(T t)
    {
        db.Insert();
    }

    public update SpecialWord(T t)
    {
        db.Update();
    }
}


public class TestController
{
    A aObj = new A();
    aObj.EngWord ="test";
    IDbConnection db = null;
    if(1)
        db = new SQLDBConnection(connString);
    else
        db = new OracleDBConnection(connectionString);

    B b = new B(db);

    Evaluator<A> evaluator = new Evaluator<A>(editor.Rule.GetRuleXml());
    bool success = evaluator.Evaluate(aObj);
}

【问题讨论】:

    标签: rule-engine business-rules codeeffects


    【解决方案1】:

    如果您使用实例外部方法,则声明类必须有一个空的构造函数,以便引擎能够实例化该类并成功调用该方法。

    在您的情况下,您可以在源中声明 Connection 属性,在评估开始之前设置其值,然后将该源作为参数传递,以便在您的外部方法中使用该连接。源类型的参数对规则作者不可见,它们在评估期间由引擎自动传递给方法。在规则 XML 中,它们被声明为 &lt;self/&gt; 参数节点。

    这可能是这样的:

    public class A
    {
       public IDbCoonection Connection { get; set; }
    
       // The rest of the source type goes here...
    }
    
    public class B
    {
       public B( ) { } // Empty constructor
    
       [Method("Is Special Word", "Indicates to test abbreviated word")]
       public bool IsSpecialWord( A source, string word )
       {
          source.Connection.CheckSpecialWord(word);
       }
    }
    

    规则如下所示:

    If Is Special Word ( test ) then Do Something
    

    请注意,规则作者不必将源作为参数传递给方法,它会自动发生。

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2021-07-31
      • 2013-10-26
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多