2

当我DbContext has been disposed error尝试使用下面提到的代码从数据库中获取数据时,我得到了。

如何解决这个问题?

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();
   }
} 
4

2 回答 2

1

问题是对象的某些部分应该在它仍在使用时被处理掉。

尝试始终以这种方式解决服务:

protected readonly IRepository<T> _exampleRepository;

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

希望这可以帮助!

于 2017-02-17T12:46:30.783 回答
1

我认为您的示例中没有足够的代码。如果您从依赖范围获取 ExampleService,它应该可以正常工作。

所以我的回答是:在构造函数中使用依赖注入,而不是使用 ResourceLocator。如果您改为在构造函数中声明依赖项并且仍然存在问题,例如,没有收到 IRepository 的实例,那么您可以确定您在 autofac 范围之外以错误的方式实例化 ExampleService,这是一个肯定的原因为了麻烦。

于 2017-02-18T13:18:16.073 回答