Exception in AddBusinessRules leaves rules in permanently indeterminate state

Exception in AddBusinessRules leaves rules in permanently indeterminate state

Old forum URL: forums.lhotka.net/forums/t/9545.aspx


rsbaker0 posted on Friday, September 17, 2010

In CSLA 3.5.1, if any sort of exception occurs during the processing of AddBusinessRules for a type, the rules for that type are basically corrupted for the duration of the process life.

    private void InitializeBusinessRules()
    {
      AddInstanceBusinessRules();
      if (!(Validation.SharedValidationRules.RulesExistFor(this.GetType())))
      {
        lock (this.GetType())
        {
          if (!(Validation.SharedValidationRules.RulesExistFor(this.GetType())))
          {
            Validation.SharedValidationRules.GetManager(this.GetType(), true);
            AddBusinessRules();
          }
        }
      }
    }

The problem is in the code above:

RulesExistFor() returns false on the first call, but the call to GetManager() will cause future calls to RulesExistFor() to return true even if the initialization did not complete successfully.  

Would it be reasonable to change this so that the shared rules for the type are discarded from the shared validation rules if an exception occurs during AddBusinessRules?

RockfordLhotka replied on Friday, September 17, 2010

What good would that do? The exception would almost certainly occur every time someone tried to use that type, so you'd just never get any rules at all.

rsbaker0 replied on Friday, September 17, 2010

In my case, it was a transient database exception that occurred, so a subsequent use of the type might very well have succeeded.

However, the "good" that it would do in the general case would be to prevent use of BO that does not properly enforce it's business rules.  If a BO can't initialize it's business rules properly, then you should not be allowed to create and use an instance of that BO.

As written, if a consumer of the type chooses to eat the exception and try again (exactly the case in my situation because the actual application where this occurred is a service that processing batch jobs offline from the client applications), then now they are given a BO that doesn't enforce the business rules, and the result could be invalid data persisted to the database.  Very bad, and moreover extremely difficult to later diagnose how it might have occurred.

RockfordLhotka replied on Friday, September 17, 2010

That makes sense, I'll add it to the wish list - though you should know that the fix will be in CSLA 4, and maybe in 3.8 - but you'll have to fix your own 3.5 code as you see fit.

rsbaker0 replied on Friday, September 17, 2010

Thanks. I'll have to upgrade to 3.8 anyway at some point, but don't mind implementing an interim fix.

Copyright (c) Marimer LLC