0
votes

I have a project asp.net core 2.1. Error occurs when a dbcontext create a query.

I create a IRouteConstraint with check url path.

public bool Match(HttpContext httpContext, IRouter route, string parameterName,
                  RouteValueDictionary values, RouteDirection routeDirection)
{   
    var routeSlug1 = (string)values["contentCategory"];
    var routeSlug2 = (string)values["content"];

    bool slugMatch = false;
    if (!string.IsNullOrEmpty(routeSlug1) && !string.IsNullOrEmpty(routeSlug2))
    {          
        //var Data = db.CmsContent.FirstOrDefault(x => x.Tag == routeSlug2 && x.ContentCategory.Tag == routeSlug1); //.ToList() //The error is here!!!!
        var Data =  db.CmsContent.ToList();  //The error is here!!!!

        if (Data != null) 
        {
            return true;
        }
    }
    return slugMatch;
}

System.ObjectDisposedException: 'Cannot access a disposed object.
at Cms.Infrastructure.CmsContentConstraint.Match(HttpContext httpContext, IRouter route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection) in E:\Cms\Infrastructure\RouteConstraints.cs:line 35 at Microsoft.AspNetCore.Routing.RouteConstraintMatcher.Match(IDictionary`2 constraints, RouteValueDictionary routeValues, HttpContext httpContext, IRouter route, RouteDirection routeDirection, ILogger logger) at Microsoft.AspNetCore.Routing.RouteBase.RouteAsync(RouteContext context) at Microsoft.AspNetCore.Routing.RouteCollection.d__10.MoveNext()

1

1 Answers

2
votes

Don't reuse a DbContext... There is no need, connections are cached anyway, and gives you no appreciable benefits. However, it can introduce several problems

Put it in a using statement

using(var db = new DbContext())
{
    // much better and wont be disposed 
    db.CmsContent...
}