Skip to content
This repository was archived by the owner on Nov 2, 2018. It is now read-only.
This repository was archived by the owner on Nov 2, 2018. It is now read-only.

Cannot access a disposed object in ASP.NET Core when injecting DbContext #440

Closed
@mdmoura

Description

@mdmoura

On an ASP.NET Core project I have the following on Startup:

      services.AddDbContext<Context>(x => x.UseSqlServer(connectionString));

      services.AddScoped<IValidationService, ValidationService>();

      services.AddScoped<IValidator<Model>, ModelValidator>();

The ValidationService is as follows:

    public interface IValidationService {
      Task<List<Error>> ValidateAsync<T>(T model);
    }

  public class ValidationService : IValidationService {

    private readonly IServiceProvider _provider;

    public ValidationService(IServiceProvider provider) {
      _provider = provider;
    }

    public async Task<List<Error>> ValidateAsync<T>(T model) {

      IValidator<T> validator = _provider.GetRequiredService<IValidator<T>>();

      return await validator.ValidateAsync(model);

    }
  }

And the ModelValidator is as follows:

    public class ModelValidator : AbstractValidator<Model> {
      public ModelValidator(Context context) {
        // Some code using context
      }
    }

When I inject a IValidationService in a controller and use it as:

    List<Error> errors = await _validator.ValidateAsync(order);    

I get the error:

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. 
This may occur is you are calling Dispose() on the context, or wrapping the context in a using statement. 
If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'Context'.    

Any idea why I am having this error when using Context inside ModelValidator?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions