简体   繁体   English

如何将 DbContext 注入 NRules 类构造函数?

[英]How to inject DbContext into NRules class constructor?

I am using NRules to define rules and trying to using interface inside NRules base class but something goes wrong and I get "No parameterless constructor defined for this object" error.我正在使用 NRules 来定义规则并尝试在 NRules 基类中使用接口,但是出了点问题,我收到“没有为此对象定义无参数构造函数”错误。 Here is my Interface definition这是我的接口定义

{
    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 Class规则类

 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));

        }

    }

I have received an error when NRules begin load assembly MissingMethodException: No parameterless constructor defined for this object.我在 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();

As the error says, you can't have a rule which has a constructor containing parameters.正如错误所说,您不能拥有包含参数的构造函数的规则。

You also should be resolving the dependency inside of the rule definition, as shown in Rule Dependency on the NRules wiki.您还应该解决规则定义内部的依赖关系,如 NRules wiki 上的规则依赖关系中所示。

Your class should therefore be something like the following:因此,您的课程应该类似于以下内容:

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));

        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM