Search code examples
c#thread-safetyblazor-server-sidevalidationattribute

Is dbContext (retrieved from ValidationContext.GetService in Blazor Server Side app) thread safe?


Is dbContext (retrieved from ValidationContext.GetService in Blazor Server Side app) thread safe?

public class SomeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
        ...
        using var dbContext = (AppDbContext)validationContext.GetService(typeof(AppDbContext));
        ...
    }
}

Solution

  • I don't believe there is any instantiation of dbContext that's Thread Safe. You should instantiate another one if you need to be async.
    Here you've got it injected into an Attribute so maybe you're asking if it'll be a new one every time this gets hit? If so then yes unless you've injected it in a way that it isn't.
    Like if you're using Services.AddDbContext or Services.AddDbContextFactory it will be new and therefore the Attribute getting hit asynchronously would be fine as each would have a new context.

    See: https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/