用Prism的童鞋們都知道Module可以動態載入,那麼如何動態卸載模組(Unload module)呢?這個需求也不變態,通常有使用者登入功能,登入的時候動態載入該使用者可以訪問的模組,那麼登出的時候呢就需要動態卸載這些模組,然後用另外一個使用者登入。模組卸載這個事兒據我所知,是不可能的,這兒和這兒有討論,具體原因是這樣的:
No, it's not possible. This is a CLR restriction, not a PRISM or even a Silverlight restriction. You can only unload an entire AppDomain, not individual assemblies within the domain. If the user is logging out you could post back to the site in an unauthorized state and the whole plugin will unwind. If you're looking to manage memory during runtime, your best solution is to de-reference any objects as soon as possible to allow garbage collection to deal with them.
登出卸載Prism模組的替代實現方法
我能想到的替代方法是當使用者點擊登出成功退出以後重新整理一下瀏覽器(重新整理首頁)就行了。具體做法就是:
1. 在web項目的home.aspx的body裡寫一個重新整理的js:
<script type="text/javascript">
function RefreshSL() { window.location.reload(); }
</script>
2. 在Silverlight中引用System.Window.Brwoser,然後調用哪個js即可:
HtmlPage.Window.Invoke("RefreshSL","Invoke");
就這麼簡單。有更好的辦法請通知我。
有關Assembly.Unload的參考資料
- Why isn't there an Assembly.Unload method?
- 有關Assembly.Unload
- 完整的動態載入/卸載程式集的解決方案
- 通過應用程式定義域AppDomain載入和卸載程式集
- 動態load assembly 動態unload assembly