使用 PreApplicationStartMethod 註冊自訂的 VirtualPathProvider{轉}

來源:互聯網
上載者:User

在 ASP.NET 網站中,有一些工作必須在網站初始化階段完成,比如自訂的虛擬路徑提供器,通常情況下,我們需要在 Global.asax 中進行註冊,或者使用 App_Code 目錄中任意類的 AppInitialize 靜態方法。在 CoderZh 的 VirtualPathProvider註冊的問題 中討論了這兩種方法。

 

在 ASP.NET 4.0 中提供了一個新的特徵 PreApplicationStartMethod 允許我們在上邊初始化之前完成網站的初始化,這樣,我們可以在一個類庫項目中使用這個特徵來標記需要在網站中提前初始化的方法。但是對於多個程式集的情況下,不能保證調用程式集定義的應用程式啟動方法的順序。因此,每個註冊的開始方法應該將代碼編寫為分開運行,不應該依賴於其他註冊開始方法的副作用。

詳細說明見 MSDN 的 PreApplicationStartMethodAttribute 類

 

下面的代碼示範了如何註冊自訂的 VirtualPathProvider,網站項目中僅僅引用這個項目即可,不需要進行額外的配置了。

 

代碼 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 using System.Web;
 7 
 8 [assembly: PreApplicationStartMethod(typeof(MyNamespace.Class1), "Init")]
 9 
10 namespace MyNamespace
11 {
12 
13     public class DemoVirtualPathProvider : System.Web.Hosting.VirtualPathProvider
14     {
15     }
16 
17     public class Class1
18     {
19         public static void Init()
20         {
21             DemoVirtualPathProvider provider = new DemoVirtualPathProvider();
22             System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(provider);
23         }
24     }
25 }
26 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.