问题描述
我在评估规则时遇到了麻烦,它会初始化类B并调用默认构造函数,但是我正在通过参数构造函数注入Db Connection。请参阅以下代码和建议。
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);
}
解决方法
如果使用实例外部方法,则声明类必须具有一个空构造函数,以便引擎能够实例化该类并成功调用该方法。
在您的情况下,您可以在源中声明Connection
属性,在评估开始之前设置其值,然后将该源作为参数传递,以便在外部方法中使用该连接。规则作者看不到源类型的参数,引擎在评估过程中将它们自动传递给方法。在Rule XML中,它们被声明为<self/>
参数节点。
这是下面的样子:
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
请注意,规则作者不必将源作为参数传递给方法,它会自动发生。