Skip to content

Injecting DBContext in Validation Attribute randomly throws error: "Cannot access a disposed context instance" #53114

@sipi41

Description

@sipi41

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I created a validation attribute that uses something like db = (MyDbContext)validationContext .GetService(typeof(MyDbContext)); to get the dbcontext injected, the problem is that it randomly throws an error saying that the dbcontext has been disposed, I injected the service in the constructor and also check if dbcontext is null, and if so, it try to create a new instance of the dbcontext, and sometimes works sometimes it does not... please check my code below and the error received on blazor.

public class ConstraintsV2_Require_Resolution : ValidationAttribute
    {

        private MyDbContext db { get; set; }


        private void CreateContext(ValidationContext validationContext)
        {
            db = (MyDbContext)validationContext.GetService(typeof(MyDbContext));
        }        
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {            
            FACT_Constraint_v2 fACT_Constraint_V2 = (FACT_Constraint_v2)validationContext.ObjectInstance;

            if (value == null)
            {
                
                if (db == null) CreateContext(validationContext); //db context 
//------------------------- NEXT LINE IS WHERE ERROR IS PRODUCED
                DIM_STATUS currentStatus = db.Dim_Statuses.FirstOrDefault(f => f.status_guid == fACT_Constraint_V2.status_guid);
//------------------------- 
                if (currentStatus != null)
                {
                    if (currentStatus.status.Contains("COMPLETE", StringComparison.CurrentCultureIgnoreCase))
                    {
                        return new ValidationResult("If Status is \"COMPLETE\" a Resolution must be provided.", new List<string>() { validationContext.MemberName });
                    }
                }
            }

            return ValidationResult.Success;

        }
    }

image

Expected Behavior

Expected behavior should be to keep the instance of dbcontext I made, not to return a disposed object.

Steps To Reproduce

No response

Exceptions (if any)

image

.NET Version

7

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions