开发者

ObjectDisposedException thrown everytime a "User" (membership) object is updated

  • I am using asp.net mvc 3, entity framework with structure map for IoC.
  • I have my own custom membership provider.
  • I had the same kind of problem when I was injecting the dbcontext object and the membership instances using StructureMap so removed this for my UserRepository.
  • The UserRepository now has a DBContext property which is initialised in the constructor.

Everytime a new user is created/updated (the method doing this is wrapping the dbcontext object in using statement), the next time the dbcontext is referenc开发者_如何学Goed I get ObjectDisposedException thrown.

I don't understand what I am doing wrong. Obviously, the membership provider class isn't instantiating the userRepository object everytime it needs it and when a user is updated, the context is disposed because of the using statement. But I thought this was standard practice?

Any help is greatly appreciated.

EDITED:

There is no complex code really. The set up is:

CustomMembershipProvider overrides the standard Membership provider (config file has got the details). CustomMembershipProvider uses IUserService object that uses IUserRepository which is implemented by UserRepository that has the DBContext private object at class level.

In the UserRepository, I've got:

    public void UpdateUser(User user)
    {
        using(_db)
        {
            ... code to indicate that the user state has changed
            _db.SaveChanges();
        }
    }

Once this code is run, the request is complete. But when another request is made to retrive role information or read the user from the database (in the UserRepository class), I get the ObjectDisposedException thrown. At this point nothing related to User Or Role works because they use the same UserRepository class whose _db variable has been disposed by UpdateUser.

I initially had StructureMap resolve the DBContext object, the customMembership object etc but have had to since remove it from StructureMap's mapping.


Everytime a new user is created/updated (the method doing this is wrapping the dbcontext object in using statement), the next time the dbcontext is referenced I get ObjectDisposedException thrown.

DbContext is a disposable resource(Which implements IDisposable). So when you wrap it in a using block the context is disposed when the control flow goes out of the using block.

using(myContext)
{
   //do stuff
}

//try to access myContext after the using block throw ObjectDisposedException

You have to re-design how you use the DbContext and when you are going to dispose it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜