我有以下SpecFlow场景:
[When(@"the registration is submitted")]
public void WhenTheRegistrationIsSubmitted()
{
//var controller = _kernel.Get<AccountController>();
var factory = new HockeyDbContextFactory();
var userRepository = new Repository<User>(factory);
var cryptoService = new CryptoService();
var roleRepository = new Repository<Role>(factory);
var playerService = new Mock<IPlayerService>();
var leagueService = new Mock<ILeagueService>();
var userService = new UserService(userRepository, cryptoService, roleRepository);
var controller = new AccountController(userService, playerService.Object, leagueService.Object);
controller.Register(_registerModel);
}
它最终通过我的控制器调用以下方法:
public void RegisterUser(User user)
{
var salt = _cryptoService.GenerateSalt();
var hasedPassword = _cryptoService.HashPassword(user.Password, salt);
user.PasswordSalt = salt;
user.Password = hasedPassword;
var defaultRole = _roleRepository.GetAll().Single(x => x.RoleName == "User");
user.Roles.Add(defaultRole);
Insert(user);
}
我所有的数据库调用都很好,直到我到达以下线路:
var defaultRole = _roleRepository.GetAll().Single(x => x.RoleName == "User");
当我在那一行上断点并检查对GetAll()的调用时,我有上下文,可以查看查询。调用Single()时发生异常。现在,如果我在对GetAll()的调用上粘贴.Include(x => x.Users)
,我就可以了。这告诉我,这与懒惰有关。
我得到的错误是:错误:ObjectContext实例已被释放,不能再用于需要连接的操作
当从我的web应用程序调用RegisterUser时,我很好。当从我的规范测试中调用RegisterUser时,它将失败。有人煽动吗?
更新:
为了添加更多信息,这里是被调用的控制器操作:
[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegisterModel model)
{
if (!_userService.EmailIsUnique(model.EmailAddress))
ModelState.AddModelError("EmailAddress", "Email Address is already in use.");
if (!_userService.UserNameIsUnique(model.UserName))
ModelState.AddModelError("UserName", "User Name is already in use");
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
var user = Mapper.Map<User>(model);
_userService.RegisterUser(user);
FormsAuthentication.SetAuthCookie(model.UserName, false);
return View("RegisterSuccess");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
通过代码,我从未到达FormsAuthentication.SetAuthCookie(model.UserName, false);
我发现了问题所在。我在测试数据库中植入了以下步骤:
[BeforeFeature]
public static void BeforeFeature()
{
MappingConfig.RegisterMappings();
Database.SetInitializer(new TestDatabaseInitializer());
}
我的TestDatabaseInitializer中的上下文一定与我在场景中创建的上下文冲突。感谢Gert的评论,它让我有机会仔细看看我的其他场景中发生了什么。