The operation cannot be completed because the DbContext has been disposed. nopcommerce

469 Views Asked by At

I am getting DbContext has been disposed error when I try to get data from database using below code that have mention.

How to solved this issue ?

public class ExampleService<T> where T : Example
{
   protected readonly IRepository<T> _exampleRepository;

   public ExampleService()
   {
     _exampleRepository= EngineContext.Current.Resolve<IRepository<T>>();
   }

   public IList<T> GetService()
   {
     var query = _exampleRepository.Table;
     return query.ToList();
   }
} 
2

There are 2 best solutions below

0
On

The issue is some parts of the object should be disposed, while it still in use.

Try to always resolve the service in this way:

protected readonly IRepository<T> _exampleRepository;

To

var _exampleRepository = EngineContext.Current.Resolve<IRepository<T>>();

Hope this helps!

0
On

I think there is not enough code in your sample. It should work perfectly if you're getting ExampleService from the dependency scope.

So my answer is this: Use dependency injection at your constructor instead of using a ResourceLocator. If you declare the dependencies at the constructor instead and still have problems, like for instance, not receiving an instance of IRepository then you can be sure you're instantiating ExampleService the wrong way, outside of the autofac scope, and that is a sure cause for trouble.