0

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. 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.

 //Load rules
    var repository = new RuleRepository();
    repository.Load(x => x.From(typeof(PreferredCustomerDiscountRule).Assembly));//problem is here!
 //Compile rules
    var factory = repository.Compile();
R.J. Dunnill
  • 2,049
  • 3
  • 10
  • 21
Alex
  • 3,941
  • 1
  • 17
  • 24

1 Answers1

0

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.

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

        }

    }
  • Hey @Nicholas, the does work, but one can not use the service to look up values to be used in the "When" condition. Do you know how to use a service as part of a query? see => https://stackoverflow.com/questions/65469249/property-injection-for-nrules-within-abp – Ivan Sager Dec 27 '20 at 20:54