我在 MVC 4 中的自定义成员资格方面遇到问题,当我执行 ajax 调用以从服务器( Controller )获取部分结果时,我不断收到上下文生命周期相关的错误,错误始终是 {“提供程序已已关闭"} 或 {"已经有一个与此命令关联的打开的 DataReader,必须首先关闭它。"} 错误始终出现在自定义 RoleProvider 中。 我将尝试解释我当前使用的设置。
我继承了 Membership 和 RoleProvier 并重写了所有方法,如下所示
public class CustomRoleProvider : RoleProvider
{
private IAccountService _accountService;
public CustomRoleProvider()
{
_accountService = new AccountService();
}
public override string[] GetRolesForUser(string username)
{
return _accountService.GetRolesForUser(username);
}
}
成员(member)资格提供程序的实现方式与上面的 IAccountService 相同,IAccountService 是处理所有用户帐户和角色的服务层,所有服务层类都实现一个名为 ServiceBase 的基服务类,用于创建数据库上下文
public class ServiceBase
{
protected Context Context;
protected ServiceBase() : this("Context") {}
protected ServiceBase(string dbName)
{
IDatabaseInitializer<Context> initializer = new DbInitialiser();
Database.SetInitializer(initializer);
Context = new Context(dbName);
}
}
具有ajax功能的 Controller
[Authorize(Roles = "Administrator,Supplier")]
public class AuctionController : Controller
{
private IAuctionService _service;
public AuctionController()
{
_service = new AuctionService();
}
public AuctionController(IAuctionService service)
{
_service = service;
}
[CacheControl(HttpCacheability.NoCache), HttpGet]
public ActionResult RefreshAuctionTimes(int auctionId)
{
return PartialView("_AuctionTimer", BusinessLogic.Map.ConvertAuction(_service.GetAuction (auctionId)));
}
}
当我将 [Authorize(Roles = "Administrator,Supplier")]
属性添加到处理 ajax 调用的 Controller 时,问题才开始,我知道这是 DbContext 的生命周期在应用程序的生命周期中, Controller 服务层在每个帖子中都被销毁并重新创建,但我不确定处理此问题的最佳方法,我以前使用过此设置,但使用 DI 和 Windsor 时从未遇到过此问题IOC 正在控制上下文。
最好为提供者创建自己的数据库上下文,还是两个提供者之间存在冲突并且它们确实需要共享相同的数据库上下文?
任何帮助都会非常感谢
最佳答案
问题正是您所怀疑的。这是因为您正在创建 DbContext 的单个实例,因此遇到连接问题。如果您将它与 IOC/DI 模式一起使用,您将修复它。另一种选择是手动处理连接。
如何使用 Ninject 作为 IOC 容器来执行此操作的示例是 here 他们需要共享相同的上下文才能停止问题。
关于asp.net - MVC 自定义成员资格和角色提供者上下文生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21852667/