我正在使用NRules定义规则,并尝试在NRules基类中使用接口,但是出了一些问题,并且出现“没有为此对象定义无参数构造函数”错误。 这是我的界面定义
{
public interface ICalcDiscount
{
public void ApplyPoint(int point);
}
public class CalcDiscount:ICalcDiscount
{
private readonly UniContext _context;
public CalcPoint(UniContext context)
{
_context = context;
}
public void ApplyDiscount(int d)
{
_context.Discount.Add(new Discount{ CustomerId = 1, d= d});
_context.SaveChanges();
}
}
}
NRule类
public class PreferredCustomerDiscountRule : Rule
{
private readonly ICalcDiscount _d;
public PreferredCustomerDiscountRule(ICalcDiscount d)
{
_d = d;
}
public override void Define()
{
Book book = null;
When()
.Match(() => book);
Then()
.Do(ctx => _c.ApplyDiscount(10));
}
}
当NRules开始加载组装时,我收到一个错误 MissingMethodException:没有为此对象定义无参数的构造函数。
//Load rules
var repository = new RuleRepository();
repository.Load(x => x.From(typeof(PreferredCustomerDiscountRule).Assembly));//problem is here!
//Compile rules
var factory = repository.Compile();
答案 0 :(得分:0)
如错误所述,您不能有一个规则,该规则的构造函数包含参数。
您还应该在规则定义内部解决依赖性,如NRules Wiki上的Rule Dependency所示。
因此,您的课程应该类似于以下内容:
public class PreferredCustomerDiscountRule : Rule
{
public override void Define()
{
Book book = null;
ICalcDiscount discountService = null;
Dependency()
.Resolve(() => discountService);
When()
.Match(() => book);
Then()
.Do(_ => discountService.ApplyDiscount(10));
}
}