【问题标题】:DbContext is Disposed Exception using StructureMapDbContext 是使用 StructureMap 处理的异常
【发布时间】:2014-04-09 11:39:13
【问题描述】:

我使用 StructureMap 作为我的 IOC 容器。我创建了一个在启动时运行的种子方法,以确保数据库具有相关数据。当它运行时,我得到错误

操作无法完成,因为 DbContext 已被释放。

有问题的种子类是

public class SeedDatabase : IRunAtStartup
{
    private DbContext _context;
    private UserManager<ApplicationUser> _userManager;
    public SeedDatabase(DbContext context, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    public async void Execute()
    {
        if (!_context.Set<ApplicationUser>().Any())
        {
            //Seed Admin User
            await _userManager.CreateAsync(new ApplicationUser
                  {
                     UserName = "Admin",
                     Company = "Test Company Ltd",
                     EmailAddress = "email@emailaddress.com"
                  }, _userManager.PasswordHasher.HashPassword("Password"));

           _context.SaveChanges();
        }
    }
}

点击.SaveChanges()时出现错误

此方法仅在启动时运行一次,它在其构造函数中接受 UserManagerDbContext,这些是通过 IOC 容器提供的。

我尝试过处理每个 HttpRequest 的 DbContext,这是我的偏好,但也作为单例。然而,情况并没有改变。

这是 IOC Container 的一些设置

//convention for DbContext
public class DbContextConvention : IRegistrationConvention
{
     public void Process(Type type, Registry registry)
     {
         //be sure a new context is used for each request
         if (type.CanBeCastTo(typeof(DbContext)) && !type.IsAbstract)
         {
            registry.For(type).LifecycleIs(new UniquePerRequestLifecycle());
         }
     }
}

任何想法为什么我在它还没被使用之前就一直丢弃它?

【问题讨论】:

  • 避免使用async void,如here所述。
  • @Steven 是的,我让它同步(接口需要 void,我不想更改它)并且它工作正常。现在我明白了,这很有意义。你能把这个评论变成我的答案吗?再次感谢。

标签: entity-framework asp.net-mvc-5 ioc-container structuremap dbcontext


【解决方案1】:

问题可能是由您的 Execute 方法的异步特性引起的。此方法将几乎立即返回,并将在后台线程上继续。您可能在 Execute 返回后处理 DbContext,但此时后台操作尚未完成。相反,返回 Task 并等待该任务完成后再清理,或者使 Execute 方法同步。

【讨论】:

    猜你喜欢
    • 2010-12-17
    • 2012-12-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多