【问题标题】:Dependency Injection - EF Repository Dispose method called to soon依赖注入 - 即将调用 EF Repository Dispose 方法
【发布时间】:2013-06-28 14:39:44
【问题描述】:

我有一个 MVC4 Web 项目,并使用 Castle Windsor 作为我的 DI 容器。另外,我正在使用实体框架来访问 SQL 数据库。我想将我的 Lifestyle 设置为 PerWebRequest,但是,当我这样做时,我收到以下错误:“操作无法完成,因为 DbContext 已被释放”。

如果我使用 Transient 生活方式,则可以绕过该错误,但它会在 Entity Framework 中引入一组新问题。如何保持 PerWebRequest 的生活方式,但在调用 dispose 方法时正确?

我正在使用构造函数注入向我的存储库传递一个连接字符串来构建一个新的上下文。我也实现了 IDisposable。见下文:

public class MySqlRepository : MyRepository, IDisposable
{
    private readonly DbContext _context;

    public MySqlRepository(string connectionString)
    {
        _context = new DbContext(connectionString);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            _context.Dispose();
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
}

【问题讨论】:

  • 代码似乎是正确的。您确定使用 SqlRepository 的组件也有 PerWebReuquest 或更短的生活方式吗?

标签: asp.net-mvc-4 dependency-injection entity-framework-5 castle-windsor idisposable


【解决方案1】:

这应该不是问题。 我曾经遇到过这个问题,原因是我的容器设置不正确。

这是一个使用城堡温莎的演示。

容器是这样设置的:

container = new WindsorContainer();
container.Register(Classes.FromThisAssembly().BasedOn<Controller>().LifestylePerWebRequest());
container.Register(Classes.FromThisAssembly().InNamespace("MvcIoCDemo.Models").WithServiceDefaultInterfaces().LifestylePerWebRequest());

控制器:

public class ProductsController : Controller
{
    private readonly IProductRepository productRepository;

    public ProductsController(IProductRepository productRepository)
    {
        if (productRepository == null) throw new ArgumentNullException("productRepository");
        this.productRepository = productRepository;
    }

存储库:

public class ProductRepository : IDisposable, IProductRepository
{
    private readonly DemoDbContext context;

    public ProductRepository()
    {
        context = new DemoDbContext();
    }

在此处查看演示项目: https://github.com/kobbikobb/MvcIoCDemo

【讨论】:

    【解决方案2】:

    在更改我所有注册的组件以使用 PerWebRequest 的生活方式后,我认为我的问题源于将 IEnumerable 与实体框架一起使用。这是一个与我非常相似的问题。 stackoverflow.com/questions/9691681/… 我以为是生活方式,但可能与我与 EF 的互动方式有关。

    如果 IEnumerable,我可以通过为任何具有返回类型的存储库方法调用 .ToList() 来保留 Lifestyle.PerWebRequest。这样可以确保我需要访问的数据会在上下文被释放之前加载到内存中。

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2014-02-12
      相关资源
      最近更新 更多