我具体提到Impersonating user with Entity Framework的已接受答案,其中包含以下代码:
using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
using (var dbContext = new MyEntityFrameworkContainer())
{
...
}
我宁愿只在我的存储库中的一个地方实例化dbContext
,它实现IDisposable
,然后在处理实体时处理上下文。我不确定上面的两个using
范围是如何相互影响的,所以如何在避免使用块的同时实现此代码在模拟方面的作用?
增加:
正如下面的答案所暗示的,我可以简单地使用局部变量并“手动”确保资源被处理掉,但我关注的是内部using
中的实例化是否以任何方式影响外部{{1} }。如果这只是生命的问题,而外using
没有建立任何影响内在的背景或任何内容,那么下面的答案已经回答了我的问题。
答案 0 :(得分:2)
您可以将它们声明为2个私有字段,并在构造函数中实例化它们。
然后实现Dispose()并以相反的顺序处理它们。
当然,调用代码(业务层)应该将using(){}
模式应用于Repository实例。
嵌套使用不应该很重要。 Impersonate()
是一个影响当前线程的状态更改。使用隐含的Dispose()将调用Undo()。
答案 1 :(得分:1)
var id = ((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();
//store id
//do whatever you want, for example store this variable in a field
id.Dispose(); //remove impersonation