c# - 如何将 DbContext 注入 NRules 类构造函数?
问题描述
我正在使用 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();
}
}
}
NR规则类
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();
解决方案
正如错误所说,你不能有一个包含参数的构造函数的规则。
您还应该解决规则定义内部的依赖关系,如NRules wiki 上的规则依赖关系所示。
因此,您的课程应类似于以下内容:
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));
}
}
推荐阅读
- c# - 无效退货,原因不明
- wordpress - 为什么相同的 WordPress 功能在一个站点上运行而不在另一个站点上运行?
- angular - Jenkins npm install 对于目录 A 失败,但对于目录 B 安装成功
- codeigniter - 未定义索引:log_path in /
- javascript - 如何结合 createAppContainer 将持久性道具传递给 React Navigation 导航器?
- mysql - 将谷歌表格中的特定范围插入到 MYSQL
- java - 如何获取外部 IP 地址?
- java - 在位图上反转黑白不起作用
- c# - c# 转到文本文件中的特定行然后跳过几行并编辑
- javascript - 反应 JVectorMap 标记