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

前端 未结 1 1086
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 19:00

My role provider looks like the class below (abridged). I am running on IIS Express, and SQL 2012 Express, from VS 2012, and I get a multitude of seemingly random exceptions

相关标签:
1条回答
  • 2020-12-21 19:29

    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.

    0 讨论(0)
提交回复
热议问题