首页 > 解决方案 > 如何将 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();

标签: c#nrules

解决方案


正如错误所说,你不能有一个包含参数的构造函数的规则。

您还应该解决规则定义内部的依赖关系,如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));

        }

    }

推荐阅读