What could cause many data access exceptions using EF code first in a custom RoleProvider?

十年热恋 提交于 2019-11-29 16:20:19

Gert Arnold is on the right track with his comment. You have to realize that the RoleProvider runs as a singleton. Each time you restart your app, it is causing a new instance of this class to be constructed. As long as your application is running, it keeps using this one single instance.

I used to get the same kinds of exceptions as in your question before I realized that this class runs as a singleton. After you have that knowledge, it is not difficult to make these exceptions go away:

public class Educ8RoleProvider : RoleProvider
{
    //private readonly Educ8DbContext _dbContext = new Educ8DbContext();
    //private readonly Authorization _authorization;
    public Educ8RoleProvider()
    {
        //_authorization = new Authorization(_dbContext);
    }

    private Authorization GetAuthorization()
    {
        return new Authorization(new Educ8DbContext());
    }

    public override void Initialize(string name, NameValueCollection config)
    {
        try
        {
            base.Initialize(name, config);
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
            throw;
        }
    }
    public override bool IsUserInRole(string username, string roleName)
    {
        return GetRolesForUser(username)
            .Any(r => r.ToLower() == roleName);
    }
    public override string[] GetRolesForUser(string username)
    {
        return GetAuthorization().GetRolesForMember(username)
            .Select(r => r.Name).ToArray();
    }
}

Essentially, you want to make sure that each method call on the RoleProvider works with a brand new DbContext instance. This way, the RoleProvider singleton is not hanging onto a single DbContext that gets stale.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!