ASP.NET 2.0 BuildProvider 导论(三)

下一个话题我们来看 ASP.NET 2.0 中新增的 Profile 功能。这和我们要谈的 BuildProvider 有什么关系么?

.NET Framework SDK 的文档中有这样一段话,引起了我的兴趣。位于 System.Web.Profile.ProfileBase 类的首页上:

在启动启用了用户配置文件的应用程序时,ASP.NET 会创建一个类型为 ProfileCommon 的新类,该类从 ProfileBase 类继承。强类型访问器被添加到 profile 配置节中为每个属性定义的 ProfileCommon 类中。ProfileCommon 类的强类型访问器调用 ProfileBase 基类的 GetPropertyValueSetPropertyValue 方法,分别用于配置文件属性值的检索和设置。ProfileCommon 类的一个实例被设置为 ASP.NET 应用程序的 Profile 属性的值。

为了启用 Profile 机制,我们需要在 web.config 中进行必要的配置。比如:

<xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <connectionStrings>
    <add name="TestDB" 
      connectionString="........"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>

    <profile defaultProvider="TestProfileSqlProvider">
      <providers>
        <clear />
        <add name="TestProfileSqlProvider"
             type="System.Web.Profile.SqlProfileProvider"
             connectionStringName="TestDB"
             applicationName="Test" />
      </providers>

      <properties>
        <add name="PreferredLang" defaultValue="zh-CN" />
        <add name="PreferredTheme" defaultValue="Blue" />
        <add name="RecordsPerPage" defaultValue="20"  type="System.Int32" />
      </properties>
    </profile>

  </system.web>

</configuration>

上面的 Profile 配置,数据将被存储在 TestDB 这个 ConnectionString 所代表的那个数据库中。Profile 中添加了三个 properties:一个是 PreferredLang,代表用户最喜欢的界面语言;一个是 PreferredTheme,代表用户最喜欢的 ASP.NET 主题;一个是 RecordsPerPage,表示如果启用分页,每页显示的记录条数。注意最后一个指定了类型 int。

下面按照我说的步骤做:找一个 *.aspx.cs 文件(如果你没有用 Code-Behind,则直接在 *.aspx 的 script runat="server" 块中),比如在它的 Page_Load 方法中,输入 Profile,把鼠标放上去,你看到了什么?

比如当前这个画面的类名叫 Abc,你通过智能感知看到的应该是 “ProfileCommon Abc.Profile”,表示这个 Profile 类型是 ProfileCommon,是当前类的一个属性。

如果你继续敲一个点,你会发现这个类具有 PreferredLang (string 类型),PreferredTheme (string 类型),RecordsPerPage (int 类型)。恰好和你在 web.config 中的配置是一致的。

如果你有兴趣,可以在 Profile.PreferredLang 的后半部分,右击,“Go To Definition”,你会看到这个 ProfileCommon 的代码,当然这些代码也是自动生成的。这个 ProfileCommon 类从 ProfileBase 类继承,在基类基础上根据 web.config 的配置,添加了三个属性。

看到这里,最开头那段话的意义就明了了。

但我这篇的重点,并不在于 ProfileCommon 类本身,因为有了 DataSet 的基础,这个 ProfileCommon 也比较容易理解。我想请各位读者关注一下这个 Abc.Profile 属性。

无论是使用单文件 aspx 还是 Code-Behind 机制的 aspx/aspx.cs 双文件,我们都没有显式声明过、一个名称叫做 Profile、类型为 ProfileCommon 的属性。而且在页面的基类 Page 中,更是找不到踪影。那么这个属性是从哪儿来的?

这也是 ASP.NET 2.0 中内置的一个 BuildProvider 的作用。下一篇以 BuildProvider 的视角重新审视 ASP.NET 2.0 中的 Code-Behind 机制。(待续...)

posted on 2006-08-11 13:36  破宝  阅读(174)  评论(0编辑  收藏  举报

导航