就像我最近的大多数帖子一样,我首先要说的是,这对我来说是全新的,我正处于我理解的边缘。我正在处理一个现有的应用程序,遇到了上面的错误。
该应用程序是一个具有3层的MVC应用程序,并通过Swagger运行:
Rest
Services
DAL在服务层DependencyConfig中,我在Register方法中执行以下操作,注册上下文:
container.RegisterWebApiRequest<DbContext>(() => new LocalContext("name=DefaultConnection"));到目前为止,这一切似乎都工作得很好,因为应用程序的某些部分正在从数据库中读取和写入-尽管这个应用程序中有很多内容,我并不了解所有的内容。
接下来,在Rest层上,我有以下内容:
public class AccountController : ApiController
{
private readonly WindowsAuthenticationProvider _windowsAuthentication;
private readonly AuthorizationManager _authorizationManager;
private readonly IApplicationUserService _userService;
private readonly IProfileService _profileService;
private readonly IAccountLogsService _accountLogsService;
/// <summary>
/// Constructor
/// </summary>
/// <param name="authorizationManager">Authorization Manager</param>
/// <param name="windowsAuthentication">Enables windows reauthentication without a session</param>
public AccountController(AuthorizationManager authorizationManager, WindowsAuthenticationProvider windowsAuthentication,
IApplicationUserService userService, IProfileService profileService, IAccountLogsService accountLogsService)
{
_windowsAuthentication = windowsAuthentication;
_authorizationManager = authorizationManager;
_userService = userService;
_profileService = profileService;
_accountLogsService = accountLogsService;
}
/// <summary>
/// Get logged in user details
/// </summary>
/// <remarks>Retrieves details of the currently logged in user</remarks>
[Authorize]
[HttpGet]
[Route("")]
[ResponseType(typeof(AccountDetailsModel))]
public IHttpActionResult Details()
{
var userId = User.Identity.GetUserId<int>();
var model = //...
if (model.HasAccount)
{
var user = _authorizationManager.FindUser(User.Identity);
}
return Ok(model);
}
}还有来自服务层的:
public class AuthorizationManager
{
private readonly IApplicationUserService _userService;
public ApplicationUser FindUser(IIdentity identity)
{
var userId = identity.GetUserId<int>();
if (userId != 0)
{
return _userService.FindById(userId);
}
//...
}
}最后也是在服务层:
public class ApplicationUserService : UnitOfWork<LocalContext>, IApplicationUserService
{
private readonly UserManager<ApplicationUser, int> _userManager;
private readonly RoleManager<ApplicationRole, int> _roleManager;
/// <summary>
/// Finds a user by id
/// </summary>
/// <param name="id">User id</param>
/// <returns>ApplicationUser</returns>
public ApplicationUser FindById(int id)
{
return _userManager.FindById(id);
}
}其中ApplicationUser是DAL层上的模型。
我希望到目前为止这一切都是有意义的!
问题是,当代码到达这一行时:
return _userManager.FindById(id);它抛出一个InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
对我来说,这似乎是说它已经失去了上下文,例如数据库连接。
它似乎已经从注册方法中删除了DbContext --但我不知道为什么?
如果我像这样手动创建一个上下文:
Context.Users.Find(id);我能够检索到所需的条目,但问题再次出现-我不认为应用程序的工作方式是这样的。
所以我的问题是,为什么它要处理我的上下文,我如何才能阻止它这样做?
单步执行代码无济于事,我也没有想法了。
https://stackoverflow.com/questions/41466308
复制相似问题