我有一些方法需要以一定的服務帳戶運行,所以我做正常的事情:執行模擬的.NET自定義屬性?
public DoSomeWorkAsServiceAccount() {
...
// assume I am given tokenHandle
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
...
// do the work here
...
impersonatedUser.Undo();
}
我想避免寫在每一個方法的代碼,所以我想創造的自定義屬性:
[Impersonate(tokenHandle)]
public DoSomeWorkAsServiceAccount() {
// do the work
}
因此,這裏是我的問題:
- 這可能嗎?
- 你能告訴我一些可以避免代碼重複的東西嗎?
在此先感謝。
感謝您的回答......我希望我們有AOP。順便說一句,你的圖標真棒。 – 2009-08-18 20:53:02
不客氣!我沒有把它放在這個例子中,但是確保你在try finally finally塊中包裝你的'op'調用並且處置WindowsIdentity和WindowsImpersonationContext對象。 – akmad 2009-08-19 21:17:57