2

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();
   }
} 
Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
sangeet
  • 121
  • 6
  • If the ExampleService class is properly injected and not created by code, I can't see why you're experiencing that problem. Autofac manages the enties lifecicle preventing things like that, actually. So I'm presuming there is missing code in your sample. Just review the way you instantiate ExampleService. The main reason for this comment, anyway, is to remember you to inject your dependencies at the constructor instead of using a resource locator as you do. ResourceLocator is a pattern bad enough to be be avoided when possible. Clearly, in this case there is no reason for it. – Marco Regueira Feb 18 '17 at 13:07

2 Answers2

1

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!

Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
1

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.

Marco Regueira
  • 1,045
  • 8
  • 17