实体框架 dbContext 的释放过早

本文关键字:释放 框架 dbContext 实体 | 更新日期: 2023-09-27 18:37:24

我正在尝试使我的代码与依赖注入一起使用,但我遇到了一些问题。

我有以下代码来获取用户和关联的角色。

public virtual User GetUser(string username,string password,evolutiondbEntities context, IUserRole userRoleRepository)
        {
            User systemUser = new User();
            using(context)
            {
                systemUser = (from u in context.Users where u.Username == username && u.UserPassword == password select u).FirstOrDefault();
                List<IUserRole> roleList = userRoleRepository.GetRoles(systemUser.UserID);
                systemUser._roles = roleList;
            }
            return systemUser;
        }

GetRoles 方法的代码如下所示

public List<IUserRole> GetRoles(string userID,evolutiondbEntities context)
        {
            List<IUserRole> roleList = new List<IUserRole>();
            using(context)
            {
                roleList = (from r in context.UserRoles where r.UserID == userID select r).ToList<IUserRole>();
            }
            return roleList;
        }

代码正确获取用户,但是当它调用 GetRoles() 方法时,上下文似乎已被释放,因此失败。

注意:我知道我应该为上下文传递一个接口,但我还没有那么远。

实体框架 dbContext 的释放过早

您应该将上下文注入到服务中,并在没有using块的情况下使用它,因为在块结束时using上下文被释放。IoC 容器负责按照您的指示实例化和处置创建的对象。

所以你通常会有这个:

国际奥委会注册:

container.For<Context>().Use<Context>();

并在您的服务中:

public class SomeService : ISomeService
{
    private readonly Context _context;
    private readonly IUserRole _userRoleRepository;
    public SomeService(Context context, IUserRole userRoleRepository)
    {
        _context = context;
        _userRoleRepository = userRoleRepository;
    }
    public virtual User GetUser(string username, string password)
    {
        User systemUser = new User();         
        systemUser = (from u in _context.Users where u.Username == username && u.UserPassword == password select u).FirstOrDefault();
        List<IUserRole> roleList = _userRoleRepository.GetRoles(systemUser.UserID);
        systemUser._roles = roleList;          
        return systemUser;
    }
}

我过去在使用 Ninject 时遇到过类似的问题。如果你不使用Ninject,那么你的IoC很可能会有类似的东西。

在上下文的 Ninjects 绑定下,我不得不使用 .InRequestScope() 方法。

kernel.Bind<EmployeeDbContext>().ToSelf().InRequestScope();