I refer specifically to the accepted answer for Impersonating user with Entity Framework, which sports the following code:
using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
using (var dbContext = new MyEntityFrameworkContainer())
{
...
}
I would rather instantiate dbContext at only one place in my repositories, which implement IDisposable, and then dispose of the context when the entity is disposed of. I’m not sure how the two using scopes above affect each other though, so how can I achieve what this code does in terms of impersonation while avoiding the using blocks?
ADDED:
As answers below have suggested, I can simply use local variables and ‘manually’ ensure the resources are disposed, but my concern here is whether the instantiation in the inner using is in any way affect by the outer using. If this is only a matter of lifetime, and the outer using doesn’t establish any context or anything that affects the inner, then the below answers have answered my question.
You can declare them as 2 private fields and instantiate them in the constructor.
Then implement Dispose() and Dispose them in reverse order.
And then of course the calling code (Business layer) should apply the
using(){}pattern to Repository instances.Additional:
The nested usings should not be important.
Impersonate()is a state-change that affects the current thread. The using-implied Dispose() would call Undo().